繁体   English   中英

jQuery create element fires onclick事件

[英]jQuery create element fires onclick event

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

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

谢谢

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

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

你叫alert('test'); 并将其返回值分配给onclick 请改用:

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

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

onclick: somefunction()

至:

onclick: somefunction

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

这是更好的选择

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM