Add jQuery function to specific elements

2019-01-16 10:47发布

I know that you can add new jQuery functions by $.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()

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

9条回答
走好不送
2楼-- · 2019-01-16 11:30

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

查看更多
再贱就再见
3楼-- · 2019-01-16 11:33

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/

查看更多
贼婆χ
4楼-- · 2019-01-16 11:36

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

查看更多
男人必须洒脱
5楼-- · 2019-01-16 11:40

Use .bind() and .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.

查看更多
Juvenile、少年°
6楼-- · 2019-01-16 11:42

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 this to 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.

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();
查看更多
Deceive 欺骗
7楼-- · 2019-01-16 11:47

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')();
查看更多
登录 后发表回答