[英]How to change onclick of element onclick without immediately running?
When I click a button I want to change the onclick of the html tag. 当我单击一个按钮时,我想更改html标签的onclick。
Here's my code: 这是我的代码:
JavaScript: JavaScript的:
function reset() {
//some code 1
}
function hit() {
//some code 2
document.getElementById("htmlId").onclick = reset;
}
HTML: HTML:
<!DOCTYPE html>
<html id = "htmlId">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width height=device-height">
</head>
<body>
<button id = "btn1" onclick = "hit();" class = "btn">Hit</button>
<script src="script.js">
</script>
</body>
</html>
When I click the button I expect for some code 2 to execute and on my next click for some code 1 to execute. 当我单击按钮时,我希望执行一些代码2,并在下次单击时执行一些代码1。 But when I click both some code 1 and some code 2 execute immediately.
但是,当我同时单击某些代码1和某些代码2时,将立即执行。
If you add an empty onclick before it, reset(); 如果在其之前添加一个空的onclick,请重设(); still runs.
仍然运行。
JavaScript: JavaScript的:
function empty() {
}
function hit() {
//some code 2
document.getElementById("htmlId").onclick = empty;
document.getElementById("htmlId").onclick = reset;
}
How can I fix this? 我怎样才能解决这个问题?
There are a few things going on here that are interesting to address: 这里发生了一些有趣的事情:
onclick
property while modern practice is to use addEventListener
and removeEventListener
. onclick
属性,而现代实践中是使用addEventListener
和removeEventListener
。 Here are my suggestions: 这是我的建议:
addEventListener
instead of assigning to onclick
. addEventListener
而不是分配给onclick
。 So something like (code is not tested, but should get you started): 所以类似(代码未经测试,但应该可以让您入门):
let shouldReset = false;
document.getElementById("btnId").addEventListener('click', (e) => {
shouldReset = true;
e.stopPropagation(); // so the big HTML element doesn't get it
}
document.getElementById("htmlId").addEventListener('click', () => {
if (shouldReset) {
reset();
}
}
So clicks on the html element do nothing unless the button has been first clicked. 因此,除非首先单击该按钮,否则单击html元素不会执行任何操作。 Hope that helps.
希望能有所帮助。
Simply create another function, and attach that once the first function has executed: 只需创建另一个函数,并在第一个函数执行后附加它:
function hit() {
// you initial hit() function's code here
document.getElementById("btn1").onclick = '';
setTimeout(function(){
document.getElementById("btn1").addEventListener('click', function() {
/* define the next function */
})
}), 1);
};
or to better apply to your case : 或者更好地适用于您的情况:
function reset() { ... }
function hit() {
// you initial hit() function's code here
document.getElementById("btn1").onclick = '';
setTimeout(function(){
document.getElementById("btn1").addEventListener('click', reset)
}, 1);
};
This can be improved in many ways, but for the scope of your question it should do just fine. 这可以通过许多方式加以改进,但是对于您所考虑的问题,它应该可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.