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
You can use
.data()
to associate a named value with all the selected elements, and this value can be a function.You can later call the function with
$("selector").data("format")(someVal)
You can set a custom method using the
.data()
method.Example:
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: