我有一个 textarea
元素。在这堆遗留代码的某个地方,我相信注册了一个事件,阻止我在文本区域中输入文本。我试过下面的代码。
$('#clinicalNotesEditable').off("keyup keydown keypress change blur");
$('#clinicalNotesEditable').on("click", function() {
$(this).attr('disabled', false);
$(this).attr('readonly', false);
console.log('Click on textarea by ID');
// I can see the CLICK event is captured.
});
$('#clinicalNotesEditable').on("keyup keydown keypress", function() {
console.log('Key pressed on textarea by ID');
// I do not see this message.
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="noteseditable" id="clinicalNotesEditable" style="width: 370px !important; vertical-align: middle; display: inline-block; -ms-overflow-y: scroll;" placeholder="click here to enter a note" rows="8"></textarea>
我唯一能想到的是我没有正确使用.off()
。如何从 clinicalNotesEditable
元素中删除所有事件?
最佳答案
你可以迭代jQuery._data(<DOM element>, 'events')
并删除委托(delegate)和非委托(delegate)事件
$("body").on('click', '#clinicalNotesEditable', function() {
console.log('delegated');
});
$("body").on('click', function() {
console.log('not delegated');
});
$('#clinicalNotesEditable').on("click", function() {
$(this).attr('disabled', false);
$(this).attr('readonly', false);
console.log('Click on textarea by ID');
});
$('#clinicalNotesEditable').on("keyup keydown keypress", function() {
console.log('Key pressed on textarea by ID');
//I see this in the CONSOLE
});
var selector = '#clinicalNotesEditable';
$.each([$(window), $(document), $("*")], function(key, value) {
$.each(value, function(k, v) {
var event = $._data(v, "events");
if (event !== undefined) {
$.each(event, function(a, b) {
if (b[0].selector === selector) {
$(v).off(a, '**');
} else {
if ('#' + v.id === selector) {
$(selector).off(a);
}
}
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="noteseditable" id="clinicalNotesEditable" style="width: 370px !important; vertical-align: middle; display: inline-block; -ms-overflow-y: scroll;" placeholder="click here to enter a note" rows="8"></textarea>
关于javascript - 删除 HTML 元素上的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54523574/