jQuery create元素触发onclick事件 [英] jQuery create element fires onclick event

查看:152
本文介绍了jQuery create元素触发onclick事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jQuery创建锚,并且在创建元素时似乎触发了onclick事件.我已经使用此方法在此项目中多次创建元素,没有问题,我的杆子末端弄错了吗?

I create a anchor using jQuery and the onclick event seems be triggered when the element is created. 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);

谢谢

推荐答案

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

You're calling alert('test'); and assigning it's return value to onclick. Use this instead:

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

由于我确定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:

onclick: somefunction()

收件人:

onclick: somefunction

如果要将参数传递给通常传递给事件处理程序的event对象以外的其他函数,则只需要像我对alert('test');所做的那样将其包装在匿名函数中即可.

You only need to wrap it in an anonymous function the way I did with alert('test'); if you're passing arguments to the function other than the event object that is normally passed to an event handler.

这篇关于jQuery create元素触发onclick事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆