[英]How to set a property of an element to contain a function using jQuery?
我想將一個功能分配給DOM元素的自定義屬性。 使用jQuery。
.prop(String,function)不會將函數分配給指定的屬性,而是將調用該函數並分配其結果。
我有一個丑陋的解決方案:
$("#a").prop(
"customAttr",
function() {
return function() {
$("#a").text("B");
};
}
);
http://jsfiddle.net/rapik/fyn6zh85/
有沒有更好的方法(使用jQuery)?
我猜想您嘗試將此功能與這些對象相關聯的原因是,當應用程序中發生某些特定事件時,您可以導致調用該功能。 一種更好的方法是使用事件 。
// set up the event handler
$("#a").on('somecustomevent', function() { $(this).text("B"); });
// Then, where you want that function to be invoked, trigger it.
$("#a").trigger('somecustomevent');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.