jQuery - 在元素上调用函数

jQuery - Call a function on an element

我想像这样调用一个函数来显示和修改内容:

$('#element').someFunction();

我写了这个函数:

function someFunction(){
     $(this).show();
     //other stuff
}

但这行不通。 谁能告诉我如何解决这个问题。

您可以 extend jQuery 并创建自定义方法:

$.fn.someFunction = function() {
  return this.hide();
};

$('.element').someFunction();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="element">This should be hidden.</div>
<div class="element">This should be hidden.</div>

在内部 .hide() 将遍历每个元素,但如果您想手动执行此操作,则可以使用 .each() 方法:

$.fn.someFunction = function() {
  return this.each(function() {
    // 'this' refers to the element here
  });
};