英文:
Removing an onclick event from a div with javascript
问题
<div id="box" onclick="doSmt(var1, bar2)">
if (condition){
box.removeEventListener("click" , doSmt)}
英文:
Basically what the title says this is the code that I've tried but it doesn't work:
<div id="box" onclick="doSmt(var1, bar2)">
if (condition){
box.removeEventListener("click" , doSmt)}
答案1
得分: 2
我认为最好的方法是删除onclick
事件,而不是那个尝试
//onclick function
function doSmt(){
console.log("something");
}
//remove onclick event, this will be inside your if condition
document.getElementById('box').removeAttribute("onclick");
<div id="box" onclick="doSmt()"> div</div>
英文:
I think it's better if you remove the onclick
event instead of that attempt
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
//onclick function
function doSmt(){
console.log("something");
}
//remove onclick event, this will be inside your if condition
document.getElementById('box').removeAttribute("onclick");
<!-- language: lang-html -->
<div id="box" onclick="doSmt()"> div</div>
<!-- end snippet -->
答案2
得分: 1
根据MDN关于 removeEventListener
的文档,你无法移除作为HTML属性一部分的事件监听器。所以有两种选项:
-
在页面加载时添加事件监听器:
onClickHandler = () => doSmt(var1, var2); document.addEventListener('DOMContentLoaded', () => { document.getElementById('box').addEventListener('click', onClickHandler); }); // 稍后 if (condition) { document.getElementById('box').removeEventListener('click', onClickHandler); }
-
如果你无法修改HTML,你可以修改
doSMT
来检查是否已禁用:let disableBox = false; function doSmt() { if (disableBox) return; // ... } if (condition) { disableBox = true; }
或者,你可以通过首先访问元素,然后将属性设置为null来移除它:
<div id="myDiv" onclick="handleClick()">Click me</div>
<script>
function handleClick() {
alert("Div was clicked!");
}
// 从div中移除onclick事件
const div = document.getElementById("myDiv");
div.onclick = null;
</script>
英文:
What what I read at MDN for removeEventListener
you can't remove an event listener that is part of the HTML attribute. So there's two options:
Add the event listener on page load
onClickHandler = () => doSmt(var1, var2);
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('box').addEventListener('click', onClickHandler);
});
// and later
if (condition) {
document.getElementById('box').removeEventListener('click', onClickHandler)
Or if you can't modify the HTML you could modify doSMT
to watch for a disabled bit.
let disableBox = false;
function doSmt() {
if (disableBox) return;
// ...
}
if (condition) {
disableBox = true;
}
Or
it can be removed by first accessing the element and then setting the attribute to null
<div id="myDiv" onclick="handleClick()">Click me</div>
<script>
function handleClick() {
alert("Div was clicked!");
}
// Remove the onclick event from the div
const div = document.getElementById("myDiv");
div.onclick = null;
</script>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论