简体   繁体   中英

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 (ie 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;

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM