jQuery:在动态添加DOM元素时尝试将函数挂钩到onclick,但它会立即执行该函数 [英] jQuery: trying hook a function to the onclick when dynamically adding a DOM element, but it immediately executes the function instead

查看:135
本文介绍了jQuery:在动态添加DOM元素时尝试将函数挂钩到onclick,但它会立即执行该函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在动态地使用jQuery(我的意思是在运行时)将span元素添加到我的页面的DOM中:

I am using jQuery to dynamically (I mean at runtime) add a span element to my page's DOM:

// create add task button
$(document.createElement("span"))
    .attr({ id: activityNameHyphened + "-NewButton", name: activityNameHyphened + "-NewButton" })
    .addClass("smallButton")
    .appendTo(cell1)
    .click(CreateTaskRow(ActivityName));

问题是最后一行:我认为它会添加CreateTaskRow(ActivityName)作为处理程序跨度的onclick事件,如:

The problem is the last line: I thought it would add CreateTaskRow(ActivityName) as the handler for the onclick event of the span, just like:

<span onclick="CreateTaskRow(ActivityName);"></span>

这就是我想要的 - 但是当我在浏览器中运行它时,我可以看到使用调试器在这一行,它立即运行函数

which is what I want - but when I run it in the browser, I can see using the debugger that at this line it immediately runs the function instead.

如果我可以更清楚:CreateTaskRow()在我尝试时运行将它添加到onclick(我希望它只在用户实际点击跨度时运行)。

If I can make it clearer: CreateTaskRow() runs when I'm trying to add it to the onclick (I want it to run only when the user actually clicks the span).

知道我做错了什么吗? (如果我的问题不够明确,请告诉我)

Any idea what I'm doing wrong? (and please let me know if my question isn't clear enough)

推荐答案

您实际上正在调用该函数并传递结果到 .click()事件处理程序。请尝试使用闭包(匿名函数):

You are actually calling the function and passing the result to the .click() event handler. Try it with a closure (anonymous function) instead:

.click(function() {
    CreateTaskRow(ActivityName);
});

点击事件被解雇。

这篇关于jQuery:在动态添加DOM元素时尝试将函数挂钩到onclick,但它会立即执行该函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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