![](/img/trans.png)
[英]How do I write a jQuery function that iterates consecutively numbered selectors
[英]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.