简体   繁体   English

jQuery create element fires onclick事件

[英]jQuery create element fires onclick event

I create a anchor using jQuery and the onclick event seems be triggered when the element is created. 我使用jQuery创建一个锚点,并且在创建元素时似乎会触发onclick事件。 I've used this method of creating elements a few times with this project without a problem, have I got the wrong end of the stick? 我已经使用这种方法创建了几次这个项目的元素没有问题,我有没有错误的结束?

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

Thanks 谢谢

Looking at the jQuery documentation on this page you should be doing this: 查看此页面上的jQuery文档,您应该这样做:

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

You're calling alert('test'); 你叫alert('test'); and assigning it's return value to onclick . 并将其返回值分配给onclick Use this instead: 请改用:

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

Since I'm sure alert('test') is just an example I should also point out that if you have the same problem with some function you likely can just change your code from: 由于我确定alert('test')只是一个例子,我还应该指出,如果你对某些功能有同样的问题,你可能只需更改你的代码:

onclick: somefunction()

To: 至:

onclick: somefunction

You only need to wrap it in an anonymous function the way I did with alert('test'); 你只需要像我使用alert('test');一样将它包装在一个匿名函数中alert('test'); if you're passing arguments to the function other than the event object that is normally passed to an event handler. 如果您将参数传递给函数而不是通常传递给事件处理程序的event对象。

This is much better alternative 这是更好的选择

$("<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