gpt4 book ai didi

javascript - 如何使用 jQuery 设置元素的属性以包含函数?

转载 作者:行者123 更新时间:2023-11-30 17:15:58 26 4
gpt4 key购买 nike

我想为 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');

关于javascript - 如何使用 jQuery 设置元素的属性以包含函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26126117/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com