我有一个单击事件,当用户单击 select
时会触发该事件。具有 readonly
的元素状态。这工作得很好。
我遇到的问题是,当 readonly
状态已从 select
中删除元素,单击事件仍然存在。
<强> Here is a DEMO 。
您会注意到,当您单击select
时元素中,即使 select
,top 函数仍然运行。不再是readonly
$('select[readonly]').on("click", function(e) {
e.preventDefault();
alert('This is readonly!');
});
$('button').on("click", function(e) {
e.preventDefault();
$('#div form select').attr("readonly", false);
alert('Readonly Attr Removed!');
});
有办法解决这个问题吗?我知道我可以通过某种添加/删除类的方式来完成此任务 - 但我不想采用这种方法。
最佳答案
您只需要使用事件委托(delegate) .on()
即可,这样它将考虑按钮单击所做的 DOM 更改:
$('body').on("click",'select[readonly]', function(e) {
希望他能有所帮助。
$('body').on("click",'select[readonly]', function(e) {
e.preventDefault();
alert('This is readonly!');
});
$('button').on("click", function(e) {
e.preventDefault();
$('#div form select').attr("readonly", false);
alert('Readonly Attr Removed!');
});
select[readonly] {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div">
<form>
<div class="form-group">
<select readonly="true">
<option>Select an option</option>
<option>option 2</option>
<option>option 3</option>
</select>
</div>
</form>
</div>
<br /><br />
<button>
Remove Disabled Attr
</button>
关于javascript - 从 SELECT 中删除只读属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40260545/