问题
i want to fetch the value of data-attribute data-itemtype
based on ul > li class = "activeTab"
here is my code.
<ul class="tabs">
<li data-itemtype="1" class="activeTab"><a href="#tab1">Published</a></li>
<li data-itemtype="0" class=""><a href="#tab2">Unpublished</a></li>
</ul>
if class="activeTab"
is in first <li>
element then fetch the data attribute of first li element i.e 1 in this case and hence same applies for the second or any number of li elements.
i tried this
var itemType = $('ul.tabs').find('li.activeTab').attr('data-itemtype');
and it does not work. it shows value undefined.
Update:
i am using tabs. i want to know which tab is currently active and i need that value in javascript variable.
here is my HTML code.
<div class="widget">
<ul class="tabs">
<li data-itemtype="1"><a href="#tab1">Published</a></li>
<li data-itemtype="0"><a href="#tab2">Unpublished</a></li>
</ul>
<div class="tab_container">
<div id="tab1" class="tab_content">
<div class="widget" style="margin-top:0px;">
<div class="title"><img src="/images/icons/dark/cart3.png" alt="" class="titleIcon" /><h6>Published Items</h6></div>
<p>Content</p>
</div>
</div>
<div id="tab2" class="tab_content">
<div class="widget" style="margin-top:0px;">
<div class="title"><img src="/images/icons/dark/cart3.png" alt="" class="titleIcon" /><h6>Unpublished Items</h6></div>
<p>Content</p>
</div>
</div>
</div>
<div class="clear"></div>
</div>
the jQuery being used is this.
$.fn.contentTabs = function(){
$(this).find(".tab_content").hide(); //Hide all content
$(this).find("ul.tabs li:first").addClass("activeTab").show(); //Activate first tab
$(this).find(".tab_content:first").show(); //Show first tab content
$("ul.tabs li").click(function() {
$(this).parent().parent().find("ul.tabs li").removeClass("activeTab"); //Remove any "active" class
$(this).addClass("activeTab"); //Add "active" class to selected tab
$(this).parent().parent().find(".tab_content").hide(); //Hide all tab content
var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
$(activeTab).show(); //Fade in the active content
return false;
});
};
$("div[class^='widget']").contentTabs(); //Run function on any div with class name of "Content Tabs"
the above code does not work for me.
回答1:
Seems to be working fine.
I would use .data(...)
instead:
var itemType = $('ul.tabs').find('li.activeTab').data('itemtype');
alert(itemType);
Fiddle: http://jsfiddle.net/maniator/2GYxh/
来源:https://stackoverflow.com/questions/10247247/fetch-the-value-of-data-attribute-based-on-active-class