gpt4 book ai didi

javascript - 功能运行,即使它不应该运行

转载 作者:行者123 更新时间:2023-11-30 20:58:10 25 4
gpt4 key购买 nike

我有一个元素。用户单击它后,它会被激活,并根据下一次单击用户获得成功与否的消息。在这两种情况下,项目都会在点击后停用。

但是,即使我成功地将项目状态更改为“false”,这应该会阻止代码运行,但它会一遍又一遍地运行。这是代码:

handleBoltcuttersClicked(){
this.props.dispatch(activate('boltcutters', true));
console.log('klik');
setTimeout(() => this.chainMechanics(), 100)

}

chainMechanics(){
if(this.props.inventory.activeItem.boltcutters===true){
let clickedElement;
window.onclick = ((e)=>{
clickedElement = e.target;
if(clickedElement.id === 'chainChainedDoor'){
alert('you got it');
this.props.dispatch(activate('boltcutters', false))
} else {
this.props.dispatch(activate('boltcutters', false));
alert('try again')
console.log(this.props.inventory.activeItem.boltcutters);
}

})
}
}
<a className="ghost-button items" href="#" onClick={() => this.handleBoltcuttersClicked()}>Boltcutters</a>

被循环的部分是整个 window.onclick 函数。即使它不应该被访问,因为 bool 值不再是真的它仍然有效,我不明白为什么。

奖金问题:如您所见,我使用 setTimeout 延迟了 chainMechanics 函数,因为显然在函数触发之前商店没有足够快地更新并且它没有工作。它仅在第二次单击后才开始工作(并且它没有正常工作,因为 window.onclick 函数在第二次单击该项目时立即被触发,这是不可能的)

最佳答案

只要您执行此命令:window.onclick = ((e)=>{}),就会在窗口上注册一个事件监听器。从现在开始,窗口会监听自身的任何点击事件,并在点击后执行给定的功能。此过程独立于注册前后的代码。

所以你有两种选择来解决这个问题:

  • 要么在检查元素 ID (window.removeEventlistenter('click', functionName)) 后删除事件监听器。这仅在添加监听器时给出的函数已经有名称并且不像您的情况那样内联时才有效。详情请看这里:https://developer.mozilla.org/de/docs/Web/API/EventTarget/removeEventListener
  • 或者您在第二个点击处理程序中进行 bool 检查。因此,您可以阻止实际代码的执行,并且您不必处理添加/删除事件监听器的问题。我会推荐这个解决方案。

让我知道这是否有帮助或有任何不清楚的地方。

编辑

chainMechanics(){
let clickedElement;
window.onclick = ((e)=>{
if(this.props.inventory.activeItem.boltcutters===true){
clickedElement = e.target;
if(clickedElement.id === 'chainChainedDoor'){
alert('you got it');
this.props.dispatch(activate('boltcutters', false))
} else {
this.props.dispatch(activate('boltcutters', false));
alert('try again')
console.log(this.props.inventory.activeItem.boltcutters);
}
}
})
}

编辑2

function myFunc(e) {
let clickedElement;
if(this.props.inventory.activeItem.boltcutters===true){
clickedElement = e.target;
if(clickedElement.id === 'chainChainedDoor'){
alert('you got it');
this.props.dispatch(activate('boltcutters', false))
} else {
this.props.dispatch(activate('boltcutters', false));
alert('try again')
console.log(this.props.inventory.activeItem.boltcutters);
}
}
}

chainMechanics(){
if (window.onclick !== myFunc) {
window.onclick = ((e)=> myFunc(e))
}
}

关于javascript - 功能运行,即使它不应该运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47431189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com