我在下面有这个代码。当我运行应用程序并单击“栏”时,会显示消息The not 'current' div has been clicked
。然后,如果我点击“foo”,则不会显示该消息。我预计会显示该消息,因为我已在两个current
之间交换了课程divs
。
<div class="current">foo</div>
<div>bar</div>
$('document').ready(function(){
$('div').not('.current').on('click', function(){
alert("The not 'current' div has been clicked.")
var aux = $(this);
$('div').removeClass('current');
aux.addClass('current');
});
});
答案 0 :(得分:1)
您只需将click事件添加到“not current”元素,当您切换类时,其中一个元素仍然没有click事件。相反,你可以这样做:
$('document').ready(function(){
$('div').on('click', function(){
if ($(this).hasClass("current")){
return;
}
alert("The not 'current' div has been clicked.")
var aux = $(this);
$('div').removeClass('current');
aux.addClass('current');
});
});
答案 1 :(得分:0)
使用此代码:
$('document').ready(function(){
$('div').on('click', function(){
if($(this).hasClass('current')) return;
alert("The not 'current' div has been clicked.")
var aux = $(this);
$('div').removeClass('current');
aux.addClass('current');
});
});
检查回调中的类;)
jsfiddle here:http://jsfiddle.net/5hFv4/
答案 2 :(得分:0)
在DOM就绪时,您仅为没有类current
的div分配了click事件。因此,代码不起作用。您需要将click事件分配给所有div,并检查其中的类,如:
$('div').on('click', function (e) {
if (e.target.className === 'current') return;
console.log("The not 'current' div has been clicked.")
var $aux = $(this);
$('div').removeClass('current');
$aux.addClass('current');
});
答案 3 :(得分:0)
我认为你想要的是点击没有.current
类的div会获得click事件并交换.current
类,因为你正在使用jQuery操作dom并交换该类,它没有得到应用的新类,它需要在页面准备好时加载的元素,所以你可以将事件委托给document
,你会得到你想要的:
$(document).on('click', 'div:not(.current)', function () {
alert("The not 'current' div has been clicked.");
var aux = $(this);
$('div').removeClass('current');
aux.addClass('current');
});