可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am trying to use jQuery to do something like
if(jQuery('#id').click) {
//do-some-stuff
} else {
//run function2
}
But I'm unsure how to do this using jQuery ? Any help would be greatly appreciated.
Edit: I'm trying to run a function if the #id has been clicked and specifically it is has not been clicked then run the function 2 ? i.e. I need to check firstly that the #id has been clicked before running function2
?
回答1:
You should avoid using global vars, and prefer using .data()
So, you'd do:
jQuery('#id').click(function(){
$(this).data('clicked', true);
});
Then, to check if it was clicked and perform an action:
if(jQuery('#id').data('clicked')) {
//clicked element, do-some-stuff
} else {
//run function2
}
Hope this helps. Cheers
回答2:
The way to do it would be with a boolean at a higher scope:
var hasBeenClicked = false;
jQuery('#id').click(function () {
hasBeenClicked = true;
});
if (hasBeenClicked) {
// The link has been clicked.
} else {
// The link has not been clicked.
}
回答3:
A click is an event; you can't query an element and ask it whether it's being clicked on or not. How about this:
jQuery('#id').click(function () {
// do some stuff
});
Then if you really wanted to, you could just have a loop that executes every few seconds with your // run function..
回答4:
var flag = 0;
$('#target').click(function() {
flag = 1;
});
if (flag == 1)
{
alert("Clicked");
}
else
{
alert("Not clicked");
}
回答5:
This is all you need: http://api.jquery.com/click/
Having an "else" doesn't apply in this scenario, else would mean "did not click", in which case you just wouldn't do anything.
回答6:
You may actually mean hovering the element by not clicking, right?
jQuery('#id').click(function()
{
// execute on click
}).hover(function()
{
// execute on hover
});
Clarify your question then we'll be able to understand better.
Simply if an element isn't being clicked on, do a setInterval
to continue the process until clicked.
var checkClick = setInterval(function()
{
// do something when the element hasn't been clicked yet
}, 2000); // every 2 seconds
jQuery('#id').click(function()
{
clearInterval(checkClick); // this is optional, but it will
// clear the interval once the element
// has been clicked on
// do something else
})
回答7:
Maybe you're looking for something like this:
$(document).click(function(e)
{
if($(e.srcElement).attr('id')=='id')
{
alert('click on #id');
}
else
{
alert('click on something else');
}
});
jsfiddle
You may retrieve a pointer to the clicked element using event.srcElement
.
So all you have to do is to check the id-attribute of the clicked element.
回答8:
if you press x, x amount of times you will get the division of the checkbox by y which results into a jquery boxcheck which would be an invalid way to do this kind of thing. I hope you will have a look at this before using the .on() functions