jQuery,将自定义函数绑定到DOM元素

Ibo*_*lit 15 jquery

我的应用程序中有两个div,我希望它们具有相同签名的自定义函数,但具有不同的操作,以便我可以将"当前"div存储在变量中,并调用类似于:

myCurrentDiv.theFunction(someEventData);

$("#myFirstDiv").theFunction = function() {
    alert("theFunction on firstDiv");
}
$("#mySecondDiv").theFunction = function() {
    alert("theFunction on secondDiv");
}

Ros*_*ost 41

jQuery的理念与你想要的相反:jQuery不会使用新的属性或方法扩展任何现有的类型/对象; 它实现了所有内部.

但是如果你想用jQuery做,你有几种不同的方式:

  1. JavaScript方式:

    $("#mySecondDiv")[0].theFunction = function(a, b) { /* ... */ }
    
    Run Code Online (Sandbox Code Playgroud)
  2. jQuery.data:

    $("#mySecondDiv").data({ theFunction: function(a, b) { /* ... */ } });
    $("#mySecondDiv").data("theFunction")(1, 2)
    
    Run Code Online (Sandbox Code Playgroud)
  3. 自定义活动:

    $("#mySecondDiv").bind('my-event', function(event, a ,b) { /* ... */ });
    $("#mySecondDiv").trigger('my-event', [1, 2]);
    
    Run Code Online (Sandbox Code Playgroud)