jQuery-调用元素上的函数

jQuery - Call a function on an element

本文关键字:函数 元素 调用 jQuery-      更新时间:2023-09-26

我想调用一个函数来显示和修改如下内容:

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

我写了这个函数:

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

但这行不通。有人能给我一个如何解决这个问题的提示吗。

您可以扩展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
  });
};
相关文章: