我有这段代码:
<div class="show">Hello</div>
使用脚本:
$('.show').click(function() {
$(this).removeClass('show');
$(this).addClass('pop');
alert("show");
});
$('.pop').click(function() {
$(this).removeClass('pop');
$(this).addClass('show');
alert("pop");
});
所以我希望发生的是你会点击你好,它会说show。然后下次会说pop。然后它会在两者之间交替。然而,它被困在展会上。
我想我需要重新绑定一下这个事件。
有人可以帮我这个吗?
答案 0 :(得分:1)
请改用on
。
$('body').on('click', '.show', function() {
$(this).removeClass('show');
$(this).addClass('pop');
alert("show");
});
$('body').on('click', '.pop', function() {
$(this).removeClass('pop');
$(this).addClass('show');
alert("pop");
});
答案 1 :(得分:0)
或尝试使用toggle();
$('.show').toggle(function() {
$(this).removeClass('show');
$(this).addClass('pop');
alert("show");
},
function() {
$(this).removeClass('pop');
$(this).addClass('show');
alert("opo");
});
答案 2 :(得分:0)
您可以使用data
在元素上设置标记,而不是使用生成更短代码的类:
$('button').click(function(){
var flag = $(this).data('flag') || false;
alert(flag ? 'foo' : 'bar');
$(this).data('flag', !flag);
});
演示: http://jsbin.com/epilew/2/edit
修改强>
您可以将其扩展为使用从阵列中获取的任意数量的单词。
$('button').click(function(){
var words = ['foo', 'bar', 'hey', 'lol'];
var flag = $(this).data('flag') || 0;
var word = words[flag];
alert(word);
$(this).data('flag', flag >= words.length-1 ? 0 : ++flag);
});