简体   繁体   English

如何检查单击的元素是否包含具有特定类的元素

[英]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.我正在编写一个 Tampermonkey 脚本,如果单击某个按钮,它应该执行一些代码。

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它总是返回 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;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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