且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将自定义jQuery函数应用于与>匹配的选择器1个元素

更新时间:2022-12-11 18:13:21

在你的情况下你可以使用这个 - 它已经是一个匹配每个提供元素的jQuery对象:

In your case you can just use this - it's already a jQuery object matching each of the supplied elements:

jQuery.fn.setReadOnly = function() {
    return this.prop('readonly', true).css('background-color', '#f0f0f0');
}

在更一般的情况下,你想在每个DOM元素上明确地做某事除了在整个集合上调用jQuery函数之外,你还可以这样做:

In the more general case where you want to do something explicitly on each DOM element other than call a jQuery function on the entire collection you would do this:

jQuery.fn.myFunc = function() {
     return this.each(function() {
         ...
     });
});

在您的特定情况下这是不必要的,因为 .prop .css 调用隐式执行 .each

That's unnecessary in your particular case because the .prop and .css calls perform the .each implicitly.