Detect which tab was clicked with jQuery

2019-07-24 04:44发布

问题:

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);        
});