繁体   English   中英

如何告诉jQuery我编写的所有选择器都应限于正在处理的对象?

[英]How to tell jQuery that all selectors I write should be limited to the object being worked on?

我做了这个令人难以置信的插件,它将改变世界的命运http://jsfiddle.net/4phfC/1/

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>

<script>    

$.fn.colorText = function(color) {

    $('.bar', $(this)).css('color', color);

    // a million other lines of code here...

}

$(function() {

    $("#div1").colorText("red");

});

</script>

<div id="div1" class="foo" style="width:100px;height:100px;border:1px solid green">
    <span class="bar">Hello</span>
</div>

<div id="div2" class="foo" style="width:100px;height:100px;border:1px solid green">
    <span class="bar">Good Bye</span>
</div>

为了仅使用我将插件附加到的对象内的类“ bar”来实现span标签,而不是页面上的另一个,我做了:

$('.bar', $(this)).whatever();

但是请注意,将有数百万行其他代码行进去,在整个插件的其余部分中使用此约定将有些痛苦。

从现在开始,有什么方法可以告诉jQuery,我声明的所有选择器仅适用于插件所附加的元素,因此我可以像正常情况一样使用选择器:

$('.bar').whatever();

并且不会影响正在处理的元素之外的任何“ .bar”。

不,不是我所知道的,但是您可以这样做:

$(this).find('.bar')

如果您确实想要,可以执行以下操作:

!function($) {
    function jqScoped(scope) {
        return function() {
            return $.apply(window, Array.prototype.slice.call(arguments).concat([scope]);
        };
    }
    var jqUnscoped=$;
    $.fn.colorText=function(color) {
        var jQuery=jqScoped(jqUnscoped(this)), $=jQuery;
        $('.bar').css('color', color);
    };
}(jQuery);

...但是这可能不适用于$非选择器参数(尽管我尚未测试过)。

虽然可能没有选择器,但是您可以将jQuery对象另存为变量,然后从此开始使用它。例如...

$.fn.colorText = function(color) {
   var thisBar = $('.bar', $(this));

   thisBar.css('color', color);

   // continue to use thisBar...
   // a million other lines of code here...
}

我同意关于缓存选择器的所有评论,但是如果您仍然真的想做您正在描述的事情,则可以始终将功能封装在另一个功能中。

$.fn.colorText = function(color) {
    var that = this;

    function selectInScope(selector) {
        return $(selector,that);
    }

    selectInScope('.bar').css('color', color);

    // a million other lines of code here...

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM