使用 jquery/javascript 点击切换 [英] Click toggle with jquery/javascript
问题描述
我想点击一个表格元素并让它在第一次点击时执行 x 次,如果再次点击执行 Y
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>
这就是我刚才单击一次 HTML 的内容,但我希望更改它以便可以选择一个项目,然后如果再次单击取消选择它会触发不同的功能.
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);
});
这使用 jQuery 的 .data
特性将按钮的点击状态存储在按钮元素本身中.
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
}
});
})();
如果 .on
调用和 state
变量声明在具有相同效果的 jQuery document.ready
处理程序中.
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屋!