preventDefault并传递click事件侦听器的参数

时间:2017-03-25 05:21:50

标签: javascript html

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

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。在此先感谢!!!

3 个答案:

答案 0 :(得分:2)

&#13;
&#13;
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;
&#13;
&#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()

&#13;
&#13;
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;
&#13;
&#13;