jQuery创建元素时触发onclick事件

4

我使用jQuery创建了一个锚点,但是在元素创建时onclick事件似乎被触发了。我在这个项目中已经使用了这种方法创建元素几次了,没有问题,难道我理解错了吗?

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

谢谢

3个回答

8

查看此页面上的jQuery文档,您应该这样做:

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

6

你正在调用 alert('test'); 并将其返回值赋给 onclick。请改用以下方法替代:

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

我相信 alert('test') 只是一个例子,我也应该指出,如果你遇到某个函数有同样的问题,你很可能可以通过改变你的代码来解决:

onclick: somefunction()

致:

onclick: somefunction

如果你除了通常传递给事件处理程序的event对象之外,还要传递其他参数到函数中,那么你只需要像我使用alert('test');时所做的那样将其包装在一个匿名函数中。


扶额 没想到那个,谢谢。我会在11分钟后接受的。 - piddl0r

5
这是更好的替代方案。
$("<a/>", {
   href: '#',
    name: 'link_html_edit',
    id: 'link_html_edit',
    html: 'input HTML text'
}).bind('click',function(){ // your function}).appendTo("body");

我在那个例子中遇到了这个错误: Uncaught DOMException: Failed to execute '$' on 'CommandLineAPI': '<a/>' is not a valid selector. at <anonymous>:1:1 不过看起来还是有道理的... - Craig Lambie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接