在按钮单击之后,如何删除EventListener



我有一个内容可编辑的div:

<div id="editor" contenteditable="true">

我有两个按钮:

<div id="button1" onclick="javascript()">

<div id="button2" onclick="javascript()">

两个按钮都调用相同的JavaScript功能,因此每次单击一个按钮时,都会重复此功能。例如:

当我单击按钮1时,脚本将EventListener添加到编辑器中。我用它来保存某些键盘上的编辑器的内容。

当我单击按钮2时,需要删除EventListener,需要添加新的。我怎样才能做到这一点?

我已经尝试过:

function javascript() {
// remove the eventlistener 
editable.removeEventListener('keydown', keydownsave, true);
var editable = document.getElementById('editor');
editable.addEventListener('keydown', keydownsave, true);
keydownsave = function(e) {
    // execute only if certain keys are pressed. 
    var toets = e.keyCode;
    var ctrls = e.ctrlKey;
    if (toets == 32 || toets == 13 || ctrls == true && toets == 83)

但这无效。

您可以使用unbind来执行此操作。打开

$('#t').click(function() {
alert('clicked')
})
$('#t').on('mouseover',function() {
$(this).html('mouse over')
})
$('#t').on('mouseout',function() {
$(this).html('button with event listeners')
})
function removeEventListeners() {
$('#t').unbind()
$('span').html('this button has no events')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id=t>button with event listeners</button>
<span>this button has click, mouse over and mouse out event</span>
<br>
<button onclick="removeEventListeners()">remove event listeners</button>

我实际上创建了一堆这些Div Button:

<div id="subchaptertitle" data-chapid="1" data-subid="1" onclick="javascript:open_editor()">bos in brand</div>

每个按钮都有不同的数据,并且使用onclick启动函数open_editor

以这种方式,每次单击其中一个按钮时,都会调用该函数的新实例。但是这些功能永远不会关闭,这意味着它们在后台继续运行,打破了我保存的东西的方式。

我实际需要的是在再次调用同一函数之前,用它的EventListener结束先前的函数。这可能在JavaScript?

最新更新