How to add functions to some jQuery objects, but not others?

前端 未结 4 997
我寻月下人不归
我寻月下人不归 2021-02-07 08:37

Let\'s say I have a

    list:

      ...

    I want to select it with jQuery, then add s

4条回答
  •  Happy的楠姐
    2021-02-07 09:11

    You can make your own jQuery methods as follows:

    $.fn.addProduct = function(){
      var myObject = $(this);
      // do something
    }
    
    // Call it like:
    $("ul.products").addProduct();
    

    This is a bit tricky though because you are making methods that are very specific to lists. So, to be sure you should at least add some checking on the object's type and handle the code correctly if the current object is, let's say an input element.

    An alternative is to make a normal Javascript method that receives the list as a parameter. That way you can make a more list specific method.

提交回复
热议问题