2010-07-06 84 views
0

我試圖給一個按鈕一個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的變量。

+0

你真的應該考慮使用像jquery這樣的js庫,因爲它使得這個al更輕鬆並且跨瀏覽器兼容。這就是說.. 什麼瀏覽器你試圖在這個測試? – spinon 2010-07-06 21:10:34

+0

@spinon我在Chrome中測試,但它需要在IE,FF和Chrome中工作 – Jason 2010-07-06 21:14:01

回答

0

這聽起來像jQuery領土在這裏。一旦你瞭解了jQuery的各種細節,像這樣的事情是一個很好的照顧,你會發現自己寫的JavaScript少得多。

首先,從http://jquery.com/

得到的jQuery然後把這個在你的代碼綁定事件:

$('#idOfElementToBindClickEvent').click(function(){ 
    alert('Error.'); 
}); 

jQuery的基本上提供了一種方法來操作使用類似CSS選擇器的元素。

2

在對它進行查詢之前,您需要等待DOM樹的創建。

確保這一切發生後 DOM樹已經建成時創建一個範圍內:

window.onload = function() { 
    document.getElementById(subDiv).onclick = function() { alert('Error. There is an error on the the page. Please correct that then submit the page'); }; 
}; 
+0

調用此命令時已經加載的頁面。只有當輸入框更改並且不驗證時纔會調用進行調用的函數。此時應該已經加載DOM樹,如果不是的話? – Jason 2010-07-06 21:13:14

1

的document.getElementById()將一個包含你的元素的ID字符串試圖找到。假設你正在尋找id爲'subDiv'的元素,你應該調用document.getElementById('subDiv')。

(也有可能是在你的代碼的變量subDiv是包含ID的字符串,而是因爲你沒有提到它我假設它沒有。)

編輯:如果您將使用virstulte的關於使用jQuery的建議,您會將一個函數附加到document.ready事件中,以確保DOM在您的代碼運行時已經生成。例如:

$(document).ready(function() { 
    $("#subDiv").click(function() { alert("Test!"); }); 
}); 
+0

subDiv是一個包含id的變量。對於那個很抱歉。 – Jason 2010-07-06 21:11:24

+0

啊,那就像Jacob說的那樣 - DOM還沒有初始化。我也會考慮virstulte檢查jQuery的出色建議。我編輯了我的答案,將Jacob和virstulte的代碼結合起來。 – Faisal 2010-07-06 21:14:11

0

嘗試

document.getElementById(subDiv).onclick = alert('Error. There is an error on the the page. Please correct that then submit the page'); 

function redAlert() { 
    alert('Error. There is an error on the the page. Please correct that then submit the page'); 
} 

document.getElementById(subDiv).onclick = redAlert(); 

第一種情況:你需要調用的函數,並且您分配一個字符串

第二種情況:您分配一個功能而你並沒有調用這個函數