将 jQuery 函数添加到特定元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4709822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:46:43  来源:igfitidea点击:

Add jQuery function to specific elements

jqueryfunctionadd

提问by

I know that you can add new jQuery functions by $.fn.someFunction = function()

我知道您可以通过以下方式添加新的 jQuery 函数 $.fn.someFunction = function()

However, I want to add functions to specific elements only. I tried this syntax and it doesn't work $('.someElements').fn.someFunction = function()

但是,我只想向特定元素添加函数。我试过这个语法,但它不起作用$('.someElements').fn.someFunction = function()

I want to do this so that I can call the function like this somewhere in the code $('someElements').someFunction();

我想这样做,以便我可以在代码中的某处调用这样的函数 $('someElements').someFunction();

采纳答案by Reigel

Use .bind()and .trigger()

使用.bind().trigger()

$('button').bind('someFunction',function() {
    alert('go away!')
});


$('button').click(function(){
    $(this).trigger('someFunction');
});

As of jQuery 1.7, the .on()method is the preferred method for attaching event handlers to a document.

从 jQuery 1.7 开始,.on()方法是将事件处理程序附加到文档的首选方法。

回答by DarkThrone

yo can do the above with this:

你可以这样做:

$.fn.testFn = function(){
    this.each(function(){
        var className = $(this).attr('class');
        $(this).html(className);
    });    
};

$('li').testFn(); //or any element you want

Test: http://jsfiddle.net/DarkThrone/nUzJN/

测试:http: //jsfiddle.net/DarkThrone/nUzJN/

回答by Drizzel

Yo, needed to do the same thing, came up with this. its nice cause you destroy the element and function goes poof! I think...

哟,需要做同样的事情,想出了这个。这很好,因为您破坏了元素并且功能变得糟糕!我认为...

var snippet=jQuery(".myElement");
snippet.data('destructor', function(){
    //do something
});
snippet.data('destructor')();

回答by Friederike

@Reigel's answer is great! However you could also use the $.fnsyntax and let your function only handle certain elements:

@Reigel 的回答很棒!但是,您也可以使用$.fn语法并让您的函数仅处理某些元素:

$.fn.someFunction = function(){
    this.each(function(){
        // only handle "someElement"
        if (false == $(this).hasClass("someElement")) {
            return; // do nothing
        }

        $(this).append(" some element has been modified");

        return $(this); // support chaining
    });    
};

// now you can call your function like this
$('.someElement').someFunction();            

See working jsfiddle: http://jsfiddle.net/AKnKj/3/

请参阅工作 jsfiddle:http: //jsfiddle.net/AKnKj/3/

回答by dan richardson

If you're wanting this function only for particular selectors, the following will work for you. I've just had a scenario where I've needed this and it works nicely.

如果您只需要特定选择器的此功能,以下内容对您有用。我刚刚遇到了一个需要它的场景,它运行良好。

$('.my-selector').each(function(){

    $(this).init.prototype.getUrl = function(){
        // do things
    };
})

then later on you can do

然后你可以做

$('.my-selector').getUrl()

without having to define it as a plugin, or use data or bind/on/trigger events.

无需将其定义为插件,或使用数据或绑定/开启/触发事件。

Obviously you can change the function to return the containing object if you want to use it in chaining by returning this

显然,如果您想通过返回在链接中使用它,您可以更改该函数以返回包含对象 this

$('.my-selector').each(function(){

    $(this).init.prototype.getUrl = function(){
        // do things
        return this;
    };
})

回答by charltoons

I actually had this use case as well, but with a cached object. So I already had a jQuery object, a toggle-able menu, and I wanted to attach two functions to that object, "open" and "close". The functions needed to preserve the scope of the element itself and that was it, so I wanted thisto be the menu object. Anyway, you can just add functions and variables all willy nilly, just like any other javascript object. Sometimes I forget that.

我实际上也有这个用例,但是有一个缓存对象。所以我已经有了一个 jQuery 对象,一个可切换的菜单,我想将两个函数附加到该对象上,“打开”和“关闭”。保留元素本身范围所需的函数就是这样,所以我想this成为菜单对象。无论如何,您可以随意添加函数和变量,就像任何其他 javascript 对象一样。有时我会忘记这一点。

var $menu = $('#menu');
$menu.open = function(){
   this.css('left', 0);
   this.is_open = true; // you can also set arbitrary values on the object
};
$menu.close = function(){
   this.css('left', '-100%');
   this.is_open = false;
};

$menu.close();

回答by Snegh

The most obvious solution is to assign a function as the object's property:

最明显的解决方案是分配一个函数作为对象的属性:

obj.prop("myFunc", function() {
  return (function(arg) {
    alert("It works! " + arg);
  });
});

Then call it on the object this way:

然后以这种方式在对象上调用它:

obj.prop("myFunc")("Cool!");

Note: your function is the return value of the outer one, see: http://api.jquery.com/prop/#prop-propertyName-function

注意:你的函数是外层的返回值,见:http: //api.jquery.com/prop/#prop-propertyName-function

回答by Carls Jr.

I'm not also sure with my answer if this will help you but just a try how about using .live?

我也不确定我的回答是否对您有帮助,但只是尝试使用 .live 怎么样?

$(selector).live(click,function(){
    //some codes here
});

回答by dsk

I did this and its working fine..

我这样做了并且它工作正常..

 function do_write(){
     $("#script").append("<script> $(\'#t"+(id_app+4)+"\').change(function(){  alert('Write Your Code here');    });<\/script>");
     console.log("<script> $(\'#t"+(id_app+4)+"\').change(function(){  alert('hello');    });<\/script>");
}

and call function from your dynamic function which is creating a dynamic control in html

并从您的动态函数调用函数,该函数在 html 中创建动态控件