简体   繁体   中英

How to check if clicked element contains element with certain class

I am writing a Tampermonkey script that should execute some code if a certain button is clicked.

It should check if the clicked button contained an icon before it was clicked. I don't know yet if that's even possible. There are many unique buttons that could be clicked.

This is the button:

<a class="btn aao_btn" id="aao_n">
  <span id="available_aao_n" class="label label-danger"><span class="glyphicon glyphicon-remove"></span>
</a>

This is what I got so far. It always returns false

$("a.aao_btn").on("click", function (e) {
  if (e.shiftKey) {
    // Execute if Shift is pressed while clicking (working)
  }
  else {
    if ( $(this).find("span").hasClass("label_danger") ) {
        // Execute if clicked button contains a danger icon
      }
    else {
       // No danger. Currently this is always the outcome.
    }
  }
  return false;
});
if ( $(this).find("span.label-danger").length ) {

Besides the typo, this would not check the status before the element was clicked. Here is what I ended up with:

var danger_check = false;

$("a.aao_btn").mouseover (function() {
    if ( $(this).find("span.label-danger").length ) {
        danger_check = true;
    }
    else {
        danger_check = false;
    }
});


$("a.aao_btn").on("click", function (e) {
  if (e.shiftKey) {
  }
  else {
    if ( danger_check ) {
        // Do this
      }
    else {
       // Do that

    }
  }
  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