2010-07-06 51 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(); 

第一种情况:你需要调用的函数,并且您分配一个字符串

第二种情况:您分配一个功能而你并没有调用这个函数