用jquery / javascript点击切换 [英] Click toggle with jquery/javascript
问题描述
我想点击一个表格元素,让它做x第一次点击,如果再次点击,执行Y
< ; td class ='p'id ='e1'onclick =myFunction2()>< img src ='person2.png'/>< / td>
这就是我刚刚为HTML所做的一切,但我希望改变这一点一个项目可以选择,然后如果再次点击取消选择,它会触发一个不同的功能。
我要去 假设(你没有说)你希望函数每次点击就被调用到 alternate :< $($'code> $('#e1')。on('click',function(){
//检索当前状态,最初未定义
var state = $(this).data('state');
//切换状态 - 第一次点击会使这个真
state =!state;
//做你的东西
if(state){
//做这个(第一次点击,第三次点击等)
} else {
//做那个
}
//将状态返回
$(this).data('state',state);
});
这使用jQuery的 .data
功能来存储或者,你可以使用一个外部变量,但是你应该把这个回调包含在一个闭包中(在这个例子中是一个 >立即调用函数表达式来避免变量成为一个全局变量:
$ p $ (function(){
var state;
$('#e1')。on('click',function(){$ b $ state =!state;
if(state){
//执行此操作(第一次点击,第三次点击等)
} else {
//执行该操作
}
});
}) ();
如果 .on
code> state 变量声明位于jQuery document.ready
处理程序中,具有相同的效果。
I want to click a table element and to have it do x the first click and if clicked again perform Y
<td class='p' id='e1' onclick="myFunction2()"><img src='person2.png'/></td>
Thats what I have for my HTML for one click just now, but I wish to change that so that an item can be selected, then if clicked again for a deselect it would then trigger a different function.
I'm going to assume (you didn't say) that you want the function to be called to alternate with every click:
$('#e1').on('click', function() {
// retrieve current state, initially undefined
var state = $(this).data('state');
// toggle the state - first click will make this "true"
state = !state;
// do your stuff
if (state) {
// do this (1st click, 3rd click, etc)
} else {
// do that
}
// put the state back
$(this).data('state', state);
});
This uses jQuery's .data
feature to store the button's click state in the button element itself.
Alternatively, you could use an external variable, but you should enclose the callback in a closure (in this case an immediately invoked function expression) to prevent the variable from becoming a global variable:
(function() {
var state;
$('#e1').on('click', function() {
state = !state;
if (state) {
// do this (1st click, 3rd click, etc)
} else {
// do that
}
});
})();
If the .on
call and the state
variable declaration are inside a jQuery document.ready
handler that would have the same effect.
这篇关于用jquery / javascript点击切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!