Reputation: 14145
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];
Upvotes: 3
Views: 10215
Reputation: 15359
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);
});
Upvotes: 1
Reputation: 5211
<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/
Upvotes: 7
Reputation: 666
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/
Upvotes: 1
Reputation: 85545
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.
Upvotes: 2
Reputation: 62488
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);
});
Upvotes: 2