我想停止按钮的提交事件,但也将参数传递给从点击触发的函数。这就是我认为可行的方法:
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。在此先感谢!!!
答案 0 :(得分:2)
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);
});
&#13;
<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>
&#13;
答案 1 :(得分:1)
您的函数接受两个参数function NL(line, event){...}
,但您仅使用一个参数NL('add new line');
来调用它。
您没有将事件发送到NL功能。
这应该有效:
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);
});
答案 2 :(得分:0)
使用event
addEventlistener()
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',event);});
&#13;
Here's the 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>
&#13;