jQuery: Run commands only if selected element has class
I have a tab system set up that uses the following structure to automatically detect new tabs:
<a href="#div1id">Show div 1</a>
<div id="div1id">Div1</div>
The thing is, I need to disable the ability to reload a tab by clicking the tab that is already showing. I have tried using .hasClass() and .is() to detect if the clicked tab was already had '.active' applied to it, but with no luck.
Here is my current code f开发者_运维百科or the animation and changes:
$(document).ready(function(){
$("#tabs li").click(function() {
$("#tabs li").removeClass('active');
$(this).addClass("active");
$(".content").hide();
var selected_tab = $(this).find("a").attr("href");
$(selected_tab).fadeIn();
});
});
You can use .delegate()
to both make it a bit more efficient and solve your issue, like this:
$(function(){
$("#tabs").delegate("li:not(.active)", "click", function() {
$("#tabs li").removeClass('active');
$(this).addClass("active");
$(".content").hide();
$($(this).find("a").attr("href")).fadeIn();
});
});
Bu using :not(.active)
in the selector, the click
handler will only execute if it does :not()
have the .active
class...also you have one event handler instead of n
event handlers, one for each <li>
.
Maybe a simple override of the click event
$(".active").click(function(){
return false;
});
There should be no reason why the following shouldn't work.
$(document).ready(function(){
$("#tabs li").click(function() {
if (!$(this).hasClass('active')) {
$("#tabs li.active").hide();
$("#tabs li.active").removeClass('active');
$(this).addClass("active");
$("#tabs li.active").fadeIn();
}
});
});
精彩评论