skip to Main Content

I’d like to attach functions to existing DOM element in a web page. Is there a way to use jQuery selectors to create a set of DOM elements and append a function to them?

I’m doing it in javascript now like so:

    var domObject;
    domObject = document.getElementById('WeatherObservation.Temperature');
    if (domObject) {
        domObject.format = function (val) {
            var fTemp = val * 9 / 5 + 32;
            var fDisp = Math.round((fTemp + Number.EPSILON) * 10) / 10;
            this.innerText = fDisp.toString();
        }
    };

2

Answers


  1. You can use .data() to associate a named value with all the selected elements, and this value can be a function.

    $(".classname").data("format", function(val) {
      var fTemp = val * 9 / 5 + 32;
      var fDisp = Math.round((fTemp + Number.EPSILON) * 10) / 10;
      this.innerText = fDisp.toString();
    });
    

    You can later call the function with $("selector").data("format")(someVal)

    Login or Signup to reply.
  2. You can set a custom method using the .data() method.

    Example:

    $('.myClass').data({
      'format': (function() {
        var fTemp = val * 9 / 5 + 32;
        var fDisp = Math.round((fTemp + Number.EPSILON) * 10) / 10;
        this.innerText = fDisp.toString();
      })
    });
    
    // Call this later:
    
    $(mySelector).data('format')(...arguments);
    

    Or, you can set a custom event using the .trigger() method. Note that events cannot return a value, so don’t use this approach if you need to return a value.

    Example:

    $('.myClass').trigger({
      'format': (function() {
        var fTemp = val * 9 / 5 + 32;
        var fDisp = Math.round((fTemp + Number.EPSILON) * 10) / 10;
        this.innerText = fDisp.toString();
      })
    });
    
    // Trigger the event:
    
    $(mySelector).trigger('format');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search