我想知道是否有任何不引人注目的方式来挂钩诸如attr,data,css等方法并调用自定义触发器?
理想情况下,我可以这样做:
$(".friend a").bind("attr.changed", changed /* data */, function(e) {
alert("The " + changed.attribute + " attribute changed from " + changed.from + " to " + changed.to + "!");
});
$(".friend").append(
$("<a/>").
attr("href", "#").
html("Friend 1").
click(function() { alert('I was clicked!'); }); // creates the element, doesn't execute since element didn't exist
$(".friends a").each(function() {
var $this = $(this);
$this.attr("rel", "friend"); // triggers "attr.changed"
});
Run Code Online (Sandbox Code Playgroud)
理想情况下,这将能够在任何元素上触发,并将attr更改,从一个对象传递到每个jQuery方法内部的触发器调用.
编写"钩子"函数非常简单:
function hook(original, wrapper) {
return function() {
wrapper.apply(this, arguments);
return original.apply(this, arguments);
}
}
Run Code Online (Sandbox Code Playgroud)
在wrapper您提供的功能将与相同的参数调用original函数,原函数本身调用之前.
使用示例:
$.fn.attr = hook($.fn.attr, function(attribute, value) {
alert('attribute: '+attribute+', value: '+value);
});
$('a.pie').attr('href', 'http://blueberry.pie');
// An alert says "attribute: href, value: http://blueberry.pie"
Run Code Online (Sandbox Code Playgroud)
(旁注:让你wrapper取消对该original功能的调用是一个简单的扩展,但这比你想要的更有用.)
您可以直接使用它来执行您想要的操作,也可以使该wrapper函数触发您以标准jquery方式监听的自定义jquery事件.
| 归档时间: |
|
| 查看次数: |
1238 次 |
| 最近记录: |