2017-03-25 90 views
0

我想停止按鈕的提交事件,但還要將參數傳遞到由點擊觸發的函數中。這是我認爲可以工作:preventDefault併爲點擊事件監聽器傳遞參數

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

你的函數接受兩個參數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); 
}); 
+0

啊!謝謝!!! –

1

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>

+0

你是最棒的!謝謝! –

0

聲明eventaddEventlistener()

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);});
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>

+0

謝謝!!!!!!!! –