我試圖給一個按鈕一個onclick事件,當一個頁面上的某個東西改變。我試圖用很多不同的方式去做,而且都沒有成功。我究竟做錯了什麼?JavaScript動態onClick問題
下面是我試過的。
document.getElementById(subDiv).onclick = function() { alert('Error. There is an error on the the page. Please correct that then submit the page'); };
document.getElementById(subDiv).onclick = "alert('Error. There is an error on the the page. Please correct that then submit the page');";
function redErrorAlert()
{
alert('Error. There is an error on the the page. Please correct that then submit the page');
}
document.getElementById(subDiv).onclick = redErrorAlert;
document.getElementById(subDiv).setAttribute('onclick',redErrorAlert(), false);
document.getElementById(subDiv).setAttribute('onclick','redErrorAlert()', false);
注意:subDiv是一個包含元素id的變量。
你真的應該考慮使用像jquery這樣的js庫,因爲它使得這個al更輕鬆並且跨瀏覽器兼容。這就是說.. 什麼瀏覽器你試圖在這個測試? – spinon 2010-07-06 21:10:34
@spinon我在Chrome中測試,但它需要在IE,FF和Chrome中工作 – Jason 2010-07-06 21:14:01