禁用 div 上的属性仍会触发单击事件

我有一个 div,其中有一个图标,我向该 div 添加了禁用属性,并且单击事件仍然会触发。所以我创建了 div 的副本并将其更改为按钮。两者都有点击事件,但点击时按钮不会触发,但 div 会触发。这是为什么,以及如何在单击 div 时停止触发单击事件?


我知道我可以在点击事件期间检查禁用属性,但想知道为什么我必须这样做以及为什么禁用属性在 div 上不起作用


$('#btn').on('click', function() {

  alert("clicked");

});


$('#btn1').on('click', function() {

  alert("clicked");

});

#btn {

  cursor: pointer;

}


#btn[disabled] {

  cursor: not-allowed;

}


#btn1 {

  cursor: pointer;

}


#btn1[disabled] {

  cursor: not-allowed;

}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />

<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />


<div id="btn" class="disabled" disabled>

  <i class="fa fa-plus"></i>

</div>


<button id="btn1" class="fa fa-undo" disabled>

click

</button>


慕哥9229398
浏览 57回答 3
3回答

哆啦的时光机

<div>没有disabled属性,点击时必须检查是否被禁用。$('#btn').on('click', function() {&nbsp; if (!$(this).prop("disabled"))&nbsp; alert("clicked");});

ABOUTYOU

禁用属性在 上不起作用div。如果您坚持不检查属性,可以使用:not()选择器。$('#btn:not(.disabled)').on('click', function() {&nbsp; alert("clicked");});'#btn:not(.disabled)'查找具有 idbtn但不具有disabled类的元素。

手掌心

您可以使用以下 css 来禁用 div 元素上的单击,因为 div 元素没有禁用属性:&nbsp;pointer-events: none;&nbsp;cursor: default;希望这有帮助..谢谢
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5