jQuery create element fires onclick事件

pid*_*l0r 4 javascript jquery element

我使用jQuery创建一个锚点,并且在创建元素时似乎会触发onclick事件.我已经使用这种方法创建了几次这个项目的元素没有问题,我有没有错误的结束?

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

谢谢

Ric*_*ard 7

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

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


Pau*_*aul 6

您正在调用alert('test');并将其返回值分配给onclick.请改用:

onclick: function(){ alert('test'); }
Run Code Online (Sandbox Code Playgroud)

由于我确定alert('test')只是一个例子,我还应该指出,如果你对某些功能有同样的问题,你可能只需要改变你的代码:

onclick: somefunction()
Run Code Online (Sandbox Code Playgroud)

至:

onclick: somefunction
Run Code Online (Sandbox Code Playgroud)

alert('test');如果你将参数传递给函数而不是event通常传递给事件处理程序的对象,你只需要像我一样将它包装在一个匿名函数中.


Tri*_*ene 5

这是更好的选择

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