2014-03-02 13 views
2

我想在javascript中調用一個動態創建的輸入的onclick函數,但無濟於事,它不工作,並且由於語法錯誤或缺少某些內容而導致頁面的其餘部分不能正常工作。我看了其他問題,我看着我的語法是正確的,但我不明白爲什麼onclick函數不起作用。如何動態創建一個onClick到JavaScript中的輸入按鈕?

JavaScript代碼:

// create an input element 
var frm = document.getElementById("result"); 
var submitBtn = document.createElement("input"); 
submitBtn.type = "submit"; 
submitBtn.value = "Confirm Purchase"; 
frm.appendChild(submitBtn); 

submitBtn.onClick function() 
{ 
    var question = prompt('Are you sure you want to purchase these items?'); 
} 
// create an input element 
var resetBtn = document.createElement("input"); 
resetBtn.type = "button"; 
resetBtn.value = "Reset All"; 
resetBtn.style = "margin:5px"; 
frm.appendChild(resetBtn); 
resetBtn.onClick function() 
{ 
var question = prompt('Are you sure you want to remove all these selected items?'); 
} 

HTML代碼:

<div id="resultForm"> 
    <h1>Your DSLR Selections...</h1> 
     <form id="result"> 
      <!--Store User Selection Text Node Element Here--> 
      <!--<p>Your DSLR budget range selected was:</p> 
      <p>The DSLR brand you selected was:</p> 
      <p>The type of photography you selected was:</p> 
      <p>The type of lenses you selected was:</p> 
      <input type="submit" value="Confirm Purchase"/> 
      <input type="button" value="Reset All"/>--> 
     </form> 
</div> 

回答

0

resetBtn.onClick = function() ... 
1

嘗試你錯過了這兩個等號

submitBtn.onClick = function() 
{ 
    ... 
} 
resetBtn.onClick = function() 
{ 
    ... 
} 
1

附加在大多數瀏覽器事件(IE 9及以上)的方法是使用的addEventListener這樣的:

element.addEventListener('click', function() { /* do stuff here*/ }, false); 

所以,你的代碼應該是這樣的:

submitBtn.addEventListener('click', function() 
{ 
    var question = prompt('Are you sure you want to remove all these selected items?'); 
} 
0

使用分配,如在

submitBtn.onClick = function() { 
    var question = prompt('Are you sure you want to purchase these items?'); 
} 
相關問題