gpt4 book ai didi

javascript - preventDefault 并为点击事件监听器传递参数

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

我想停止按钮的提交事件,但也将参数传递给从点击触发的函数。这是我认为可行的方法:

function NL(line, event){
event.preventDefault();
document.getElementsByClassName('new-line')[1].innerHTML=line;
}
document.getElementsByClassName('new-line')[0].addEventListener('click', function(){NL('add new line');});

这是 HTML:

<form class='myform'>
<div class='form-block'>
<span class='line'>1</span>
<button class='new-line'>New Line</button>
<button class='new-line'>New 2nd Line</button>
</div>
</form>

我无法更改 HTML,我只能编辑 JS。提前致谢!!!

最佳答案

function NL(line, event) {
event.preventDefault();
document.getElementsByClassName('new-line')[1].innerHTML = line;
}
document.getElementsByClassName('new-line')[0].addEventListener('click', function(event) {
NL('add new line', event);
});
<form class='myform'>
<div class='form-block'>
<span class='line'>1</span>
<button class='new-line'>New Line</button>
<button class='new-line'>New 2nd Line</button>
</div>
</form>

关于javascript - preventDefault 并为点击事件监听器传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43012855/

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