Detect which tab was clicked with jQuery

别等时光非礼了梦想. 提交于 2019-12-24 00:56:05

问题


I have some tabs:

<ul id="tabs">
    <li><a href="#tab-allData">All data</a></li>
    <li><a href="#tab-someOtherData">Some other data</a></li>
    <li><a href="#tab-xyData">xyData</a></li>
</ul>

I want to recognize which tab was clicked and remove the tab- prefix from the href.

I have tried this js function:

$('#tabs').click(function (event) {        
    activeTab = $(this).attr('href').split('-')[1];        
    FurtherProcessing(activeTab);        
});

but I get the following error:

TypeError: $(...).attr(...) is undefined activeTab = $(this).attr('href').split('-')[1];


回答1:


<ul id="tabs">
<li><a href="#tab-allData">All data</a></li>
<li><a href="#tab-someOtherData">Some other data</a></li>
<li><a href="#tab-xyData">xyData</a></li>
</ul>

$('#tabs').on("click", "li", function (event) {         
  var activeTab = $(this).find('a').attr('href').split('-')[1];
  FurtherProcessing(activeTab);        
});

Demo: http://jsfiddle.net/6dRH6/2/




回答2:


Use this: attribute-starts-with-selector

$('[href^=tabs]').click(function (event) {        
    activeTab = $(this).attr('href').split('-')[1];        
    FurtherProcessing(activeTab);        
});

And remove # from html of href.




回答3:


you can write li click event and get its anchor tag attribute:

$('li').click(function (event) {        
    activeTab = $(this).find('a').attr('href').split('-')[1];        
    FurtherProcessing(activeTab);        
});

FIDDLE DEMO




回答4:


Use a class its better for your future coding...

<li><a href="#tab-allData" class="tabs">All data</a></li>
<li><a href="#tab-someOtherData" class="tabs">Some other data</a></li>
<li><a href="#tab-xyData" class="tabs">xyData</a></li>


$('.tabs').click(function (event) {        
    var activeTab = $(this).attr('href').split('-')[1];
        alert(activeTab)
});

Working fiddle link... http://jsfiddle.net/JQnE3/




回答5:


I'm using jQuery's on method to make use of event delegation. This only binds one event listener to the ul element instead of one for each tab. You will notice the "a" selector in the on method. This makes use of event bubbling to know that it was the a tag inside the ul that was clicked.

This is the fastest and most efficient way:

http://jsperf.com/complicated-jquery-selectors

HTML

<ul id="tabs">
    <li><a href="#tab-allData">All data</a></li>
    <li><a href="#tab-someOtherData">Some other data</a></li>
    <li><a href="#tab-xyData">xyData</a></li>
</ul>

JS

$("#tabs").on("click", "a", function (event) {        
    var activeTab = $(this).attr('href').split('-')[1];
    FurtherProcessing(activeTab);        
});


来源:https://stackoverflow.com/questions/24059648/detect-which-tab-was-clicked-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!