javascript - 添加附加响应选项卡按钮

标签 javascript jquery html ajax

所以我有了这些响应式选项卡。

<ul class="tabs">
    <li><a href="#">Tab01</a></li>
    <li><a href="#">Tab02</a></li>
    <li><a href="#">Tab03</a></li>
    <li><a href="#">Tab04</a></li>
</ul> 
<div class="tab_content">

    <div class="tabs_item">
        <h4>Tab 01</h4>
        <p>Tab 01</p>
    </div>
 etc. etc.

这些都有效。如果您要添加第五个列表项和第五个 div,一切都会正常工作,并且当您单击它时,您将拥有一个新的选项卡项目,其中包含该项目的选项卡内容。

这是所有这些的代码:

$(document).ready(function() { 

(function ($) { 
    $('.tab ul.tabs').addClass('active').find('> li:eq(0)').addClass('current');

    $('.tab ul.tabs li a').click(function (g) { 
        var tab = $(this).closest('.tab'), 
            index = $(this).closest('li').index();

        tab.find('ul.tabs > li').removeClass('current');
        $(this).closest('li').addClass('current');

        tab.find('.tab_content').find('div.tabs_item').not('div.tabs_item:eq(' + index + ')').slideUp();
        tab.find('.tab_content').find('div.tabs_item:eq(' + index + ')').slideDown();

        g.preventDefault();
    } );
})(jQuery);

});

现在我也有了第二个 js 文件。这是将其他列表项添加到我的选项卡中。本质上,您单击一个按钮,然后

$(tabs).append('<li><a href="#">Tab05</a></li>');

发生了。现在这可行了,有点。您会看到一个新的列表项,显示 Tab05。您检查 HTML,它与其他列表项完全相同。但是,当您单击它时,它不会执行任何操作。它不会作为响应选项卡激活。为什么会发生这种情况?

最佳答案

jQuery 选择器在执行代码时选择 DOM 中存在的匹配元素。当您的代码进行事件绑定(bind)调用时,它们必须存在于页面上。

当您动态添加选项卡时

$(tabs).append('<li><a href="#">Tab05</a></li>');

您需要使用Event Delegation 。您必须使用.on()使用委托(delegate)事件方法。

$(document).on('event','selector',callback_function)

示例

$(document).on('click', '.tab ul.tabs li a', function(){
    //Your code
});

您应该使用最接近的静态容器来代替文档

The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.

关于javascript - 添加附加响应选项卡按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24244927/

相关文章:

javascript - 防止 Chrome 中链接点击时光标发生变化

javascript - Uncaught ReferenceError : openerp is not defined

jquery - 如何使用 jQuery 调用带有 JSON 响应的 ajax 请求?

javascript - 具有多个文件选择和添加/删除文件功能的 HTML 文件字段

html - 请求 header 的客户端部分下的 'Accept: */*' 是什么意思?

javascript - 在 JS 和 CSS 中保持文本恰好为 N 行

javascript - 从每个组合框中选择一个选项

javascript - 在javascript中构建参数数组

html - Css Selector - 隐藏来自同一类的重复元素

javascript - console.log() 不使用括号 () 不返回逻辑测试