Check which element has been clicked with jQuery

前端 未结 7 675
天命终不由人
天命终不由人 2020-12-24 07:10

I am trying to use an \'if\' statement to determine which element was clicked.

Basically I am trying to code something along the lines of:

if (the el         


        
7条回答
  •  执念已碎
    2020-12-24 07:33

    Another option can be to utilize the tagName property of the e.target. It doesn't apply exactly here, but let's say I have a class of something that's applied to either a DIV or an A tag, and I want to see if that class was clicked, and determine whether it was the DIV or the A that was clicked. I can do something like:

    $('.example-class').click(function(e){
      if ((e.target.tagName.toLowerCase()) == 'a') {
        console.log('You clicked an A element.');
      } else { // DIV, we assume in this example
        console.log('You clicked a DIV element.');
      }
    });
    

提交回复
热议问题