jquery函数调用多次在类名上需要防止

时间:2013-05-19 09:18:17

标签: jquery jquery-plugins

我需要在 LIST ITEM 点击时调用js功能但是当事件触发时它会调用事件次数

JS

$('.first').click(function () {

    //remove previous class and add it to clicked tab
    items.removeClass('current');
    $(this).addClass('current');

    $('#v-nav>div.tab-content').hide().eq(items.index($(this))).show();

    window.location.hash = $(this).attr('tab');
});

HTML

<div id="v-nav">
                <ul>

                    <li tab="tab1" class=" first CmclTabCss  current "> <span class="spn_InerCom"> Commercial Sector </span> <span class="tab1Current spn_Nmbr"> </span></li>
                    <li tab="tab2" class="first DMTabCss"><span class="spn_InerDip">Diplomatic Missions</span><span class="tab1CurrentD spn_Nmbr"></span></li>
                    <li tab="tab3" class="first GovTabCss"><span class="spn_InerGov">Government Sector</span><span class="tab1CurrentG spn_Nmbr"></span></li>
                    <li tab="tab4" class="first WrldTabCss"><span class="spn_InerWld">Outside Kingdom</span><span class="tab1CurrentW spn_Nmbr"> </span></li>
                    <li tab="tab5" class="first ImgTabCss"><span class="spn_InerImg">Images</span><span class="tab1CurrentI spn_Nmbr"> </span></li>
                    <li tab="tab6" class="first"><span class="spn_InerNews">News Archive</span><span class="tab1CurrentN spn_Nmbr"> </span></li>

                    <li tab="tab7" class="first PplTabCss"><span class="spn_InerIndual">Site Users</span><span class="tab1CurrentIndual spn_Nmbr"></span></li>

                </ul>
</div>

1 个答案:

答案 0 :(得分:1)

您提供的代码是正确的。请在此处查看:jsfiddle

代码的其他部分必须多次触发click处理程序。

对于所描述的问题,此代码完成了工作(为清楚起见,省略了您的特定代码):

$('.first').click(function () {
    $('.first').removeClass('current');
    $(this).addClass('current');
    window.location.hash = $(this).attr('tab');
});