2011-09-01 103 views
4

我使用jQuery创建一个锚点,并且在创建元素时触发onclick事件。我已经使用this method这个项目几次创建元素没有问题,我得到了棒的错误结局?jQuery创建元素触发onclick事件

jQuery('<a/>', { 
    href: '#', 
    name: 'link_html_edit', 
    id: 'link_html_edit', 
    html: 'input HTML text', 
    onclick: alert('test') 
}).appendTo(spanDefaultValue); 

感谢

回答

6

你打电话alert('test');并赋予它的返回值onclick。因为我敢肯定alert('test')仅仅是一个例子,我还应该指出的是,如果你有一些功能相同的问题,你可能可以刚刚从改变你的代码

onclick: function(){ alert('test'); } 

onclick: somefunction() 
使用这个代替

要:

onclick: somefunction 

你只需要包装在一个匿名函数,我做了alert('test');如果你传递参数传递给其他函数的方式通常传递给事件处理程序的event对象。

+0

*捂脸*没想到的,谢谢。我会在T减11分钟后接受 – piddl0r

+0

@ piddl0r谢谢! :) – Paulpro

6

综观此页面上的jQuery的文档,你应该这样做:

$("<a/>", { 
    href: '#', 
    name: 'link_html_edit', 
    id: 'link_html_edit', 
    html: 'input HTML text', 
    click: function(){ 
    alert('test'); 
    } 
}).appendTo("body"); 
+0

干杯! PaulPRo只是把你打败了。 – piddl0r

4

这是更好的选择

$("<a/>", { 
    href: '#', 
    name: 'link_html_edit', 
    id: 'link_html_edit', 
    html: 'input HTML text' 
}).bind('click',function(){ // your function}).appendTo("body");