每个元素上的 jQuery 插件
我为我正在构建的系统创建了一个可重用的插件。只要页面上只有 1 个元素,一切似乎都可以正常工作。如果我有 2 个,则只需单击一下即可隐藏链接和面板。如何确定插件的范围以使其在每个插件上独立工作?
提前致谢。
该插件用于创建选项卡,如下所示:
(function($){
$.fn.wbTabs = function() {
return this.each(function(){
// caching selectors
$this = $(this);
$tabLinks = $this.find('.tabs li a');
$firstTab = $this.find('.tabs li:first a');
$panels = $this.find('.panel');
// function on tab click
$tabLinks.click(function() {
$panels.hide();
$tabLinks.removeClass('active');
$(this).addClass('active').blur();
var panel = $(this).attr('href');
$(panel).show();
// prevent link from clicking
return false;
});
// make first tab active
$firstTab.click();
});
};
})(jQuery);
然后我用以下命令调用该插件:
$('.wb-tabs-container').wbTabs();
I created a re-usable plugin for a system I'm building. All seems to work fine as long as I only have 1 element on the page. If I have 2, the links and panels hide for both on a single click. How do I scope the plugin to work independently on each?
Thanks in advance.
The plugin is for tab creation and goes like this:
(function($){
$.fn.wbTabs = function() {
return this.each(function(){
// caching selectors
$this = $(this);
$tabLinks = $this.find('.tabs li a');
$firstTab = $this.find('.tabs li:first a');
$panels = $this.find('.panel');
// function on tab click
$tabLinks.click(function() {
$panels.hide();
$tabLinks.removeClass('active');
$(this).addClass('active').blur();
var panel = $(this).attr('href');
$(panel).show();
// prevent link from clicking
return false;
});
// make first tab active
$firstTab.click();
});
};
})(jQuery);
Then I call the plugin with this:
$('.wb-tabs-container').wbTabs();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在插件中声明变量 var 就可以了。您正在设置全局变量,这最终会破坏您的插件(并且无论如何都会在某些浏览器中失败)。小提琴:http://jsfiddle.net/brentmn/uJbxz/3/
Declare your variables, var, inside your plugin and you'll be good. You're setting global vars which ends up breaking your plugin (and will fail in some browsers anyway). fiddle: http://jsfiddle.net/brentmn/uJbxz/3/
我可能会尝试不同的选择器方法:
这对于浏览器来说也是一个更快的过程。
I would possibly try a different selector approach:
This is also a much quicker process for the browser.
jQuery 插件/创作 指南建议“使用 jQuery 的数据方法是跟踪基于每个元素的变量。”这正是您所需要的。
还有其他方法,主要利用闭包,但数据方法更直观。
建议您采用推荐的插件模式,特别注意第6.3节数据。这很容易。
The jQuery Plugins/Authoring guidelines advise that "using jQuery's data method is a great way to keep track of variables on a per element basis." This is exactly what you need.
There are other approaches, chiefly exploiting closures but the data method is more intuitive.
Suggest you adopt the recommended plugin pattern with particular attention to section 6.3 Data. It's quite easy.