How do I determine if something has been clicked in jQuery on the first load?
I am trying to set a javascript variable to be one of a few options.
If one of a few specific link shas not been clicked (i.e. the first page load), then the variable should be set to 0 or 1 (the default value).
If it has been clicked, then I want it to get a number associated with that link.
So say the html looks like this:
开发者_运维知识库<a href=""><img src="icon2.png" id="icon-2"></a> |
<a href=""><img src="icon3.png" id="icon-3"></a> |
<a href=""><img src="icon4.png" id="icon-4"></a> |
The jQuery variable would be something like:
var icon_num = 2; // If 'icon-2' is clicked, etc.
You could do something like this:
var icon_num = 0;
$("#someContainer img").click(function() {
icon_num = parseInt(this.id.replace("icon-",""), 10);
});
Or, give them a data attribute that includes only the ID, like this:
<img src="icon2.png" data-id="2" />
This would simplify your code a bit, down to:
var icon_num = 0;
$("#someContainer img").click(function() {
icon_num = parseInt($(this).attr("data-id"), 10);
});
example
var icon_num = null; // empty select
$('a').bind('click', function(ev) {
ev.stopPropagation();
icon_num = $(this).find('>img').attr('id').split('-')[1];
return false;
});
精彩评论