jquery - 如何创建 jQuery Code Pattern?

标签 jquery

我使用本教程中的代码:jacklmoore.com/notes/jquery-tabs .

<ul class='tabs'>
    <li><a href='#tab1'>Tab 1</a></li>
    <li><a href='#tab2'>Tab 2</a></li>
    <li><a href='#tab3'>Tab 3</a></li>
</ul>
<div id='tab1'>
    <p>Hi, this is the first tab.</p>
</div>
<div id='tab2'>
    <p>This is the 2nd tab.</p>
</div>
<div id='tab3'>
    <p>And this is the 3rd tab.</p>
</div>

脚本:

$('ul.tabs').each(function(){
    // For each set of tabs, we want to keep track of
    // which tab is active and it's associated content
    var $active, $content, $links = $(this).find('a');

    // If the location.hash matches one of the links, use that as the active tab.
    // If no match is found, use the first link as the initial active tab.
    $active = $($links.filter('[href="'+location.hash+'"]')[0] || $links[0]);
    $active.addClass('active');
    $content = $($active.attr('href'));

    // Hide the remaining content
    $links.not($active).each(function () {
        $($(this).attr('href')).hide();
    });

    // Bind the click event handler
    $(this).on('click', 'a', function(e){
        // Make the old tab inactive.
        $active.removeClass('active');
        $content.hide();

        // Update the variables with the new link and content
        $active = $(this);
        $content = $($(this).attr('href'));

        // Make the tab active.
        $active.addClass('active');
        $content.show();

        // Prevent the anchor's default click action
        e.preventDefault();
    });
});

如果我想在一页上有多个选项卡系统,我必须重复脚本代码:

$('ul.tabs2').each(function(){...});
$('ul.tabs3').each(function(){...});

我不想有很多类似代码的副本。是否可以为示例中的类似代码行创建一种代码模式?

var = xxx
$('ul.tabs').each(function(){
  xxx
});
$('ul.tabs2').each(function(){
  xxx
});
$('ul.tabs3').each(function(){
  xxx
});

最佳答案

您可能想要的是将其变成一个 jQuery 插件,您可以在元素集合上调用它:

$.fn.myTabs = function() {

  return this.each(function() {

    // All code here

  });

};

$('.tabs2, .tabs3').myTabs();

关于jquery - 如何创建 jQuery Code Pattern?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13301196/

相关文章:

javascript - 如何允许用户使用此 JQuery 示例关闭幻灯片?

jQuery - 无法使用 twitter bootstrap 的日期选择器禁用过去的日期

ruby-on-rails-3 - 在ajax中设计处理注销重定向

javascript - jquery图像替换?

html - <a href ="javascript:void(0);"> 相对于 <span> 链接文本 </span> 的任何优势

php - 具有高级(列)过滤的 CRUD?

javascript - 在 jQuery UI 模态对话框中显示 iframe 的加载动画

javascript - 如何通过模态向 jQuery 表中插入新条目?

jquery - 如何使用 javascript/jquery 仅在点击事件上绘制 Google 饼图?

Javascript getJson 回调不起作用(这有什么问题?)