jQuery不当的onclick火

时间:2018-12-12 12:41:10

标签: jquery onclick

如果我尝试单击任何按钮,那么我只是在检查是否存在类名“ sale”,否则就无法保存,例如,如果我单击“ PENDING”按钮,我不想保存但是当我单击任何按钮时,都会触发提交单击

如果我单击PENDING或REMOVE按钮将不会触发

$('.submit').on("click",function(){

只需控制台“无操作”即可

https://jsfiddle.net/alimuhammadtn/5co7431a/3/

$(function() {
  $('.action').on("click", function() {
    if ($(this).hasClass('sale')) {
      $('.submit').on("click", function() {
        console.log('##saved....')
      });
    } else {
      console.log('No action');
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="action sale">
  <input type="button" class="submit" value="SALE"> <br>
</div>
<div class="action pending">
  <input type="button" class="submit" value="PENDING"> <br>
</div>
<div class="action remove">
  <input type="button" class="submit" value="REMOVE">
</div>

1 个答案:

答案 0 :(得分:1)

我不确定您要从描述中得到什么,但我认为您的意思是:

$(function() {
  $('.submit').on("click", function() {
//        if ($(this).closest("div").is('.sale')) {
    if ($(this).parent().is('.sale')) {
        console.log('##saved....')
    } else {
      console.log('No action');
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="action sale">
  <input type="button" class="submit" value="SALE"> <br>
</div>
<div class="action pending">
  <input type="button" class="submit" value="PENDING"> <br>
</div>
<div class="action remove">
  <input type="button" class="submit" value="REMOVE">
</div>

但是为什么不这样呢?

$(function() {
  $('.submit').on("click", function() {
    if ($(this).is('#sale')) {
        console.log('##saved....')
    } else {
      console.log('No action');
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="action">
  <input type="button" class="submit" id="sale" value="SALE" />
</div>
<div class="action">
  <input type="button" class="submit" id="pending" value="PENDING" />
</div>
<div class="action">
  <input type="button" class="submit" id="remove" value="REMOVE" />
</div>