2014-11-22 34 views
-1
<button name="button" id="button">convert</button> 

var convert_button = document.getElementsByTagName("button"); 

var convert = function() { 
    console.log('button is clicked'); 

}; 

//set the click handler to the convert 

convert_button.onclick = convert; 
+1

歡迎來到Stack Overflow。請描述你的問題。 – Celeo 2014-11-22 20:54:27

回答

1

document.getElementsByTagName返回HTMLCollection(至極是像對象陣列)。

// Supply index 
var convert_button = document.getElementsByTagName("button")[0]; 

,或者你可以use喜歡這個按鈕的id

var convert_button = document.getElementById("button"); 

檢查this fiddle

+0

現在它說「Uncaught TypeError:無法設置undefinedunit_converter.js的屬性'onclick':18(匿名函數)」 – 2014-11-22 21:42:45

+0

@moy_ted:請注意'

0

編輯:

如你所描述和調整

上的jsfiddle作品的代碼由他人。

http://jsfiddle.net/cm09psmf/1/

編輯完

使用的getElementById代替的getElementsByTagName:

var convert_button = document.getElementById("button"); 

的getElementsByTagName返回,你需要在它們之間迭代陣列狀物體,但如果你只有一個你頁面,你可以這樣做:

var convert_button = document.getElementsByTagName("button")[0]; //0 for first button 
+0

現在它說「Uncaught TypeError:無法設置屬性'onclick'undefinedunit_converter.js:18(匿名函數)」 – 2014-11-22 21:43:13

+0

它適用於JSFiddle,所以它必須是你的代碼中的其他東西http://jsfiddle.net/cm09psmf/ 1/ – user2782001 2014-11-22 23:15:54

0
<button name="button" id="button">convert</button> 

//var convert_button = document.getElementsByTagName("button"); 
//this is wrong; returns an 
//array not a single object 

var convert_button = document.getElementsByTagName("button")[0]; 

var convert = function() { 
    console.log('button is clicked'); 
}; 

//set the click handler to the convert 

convert_button.onclick = convert; 
+0

虐待嘗試讓我們看看:)非常感謝 – 2014-11-22 21:38:27

+0

現在它說:「Uncaught TypeError:無法設置屬性'onclick'的undefinedunit_converter.js:18(匿名函數)」 – 2014-11-22 21:50:55

相關問題