[英]How to add onclick event in dynamicly add html code via JavaScript?
I try to add some list element in loop via JS. 我尝试通过JS在循环中添加一些列表元素。 Every element
<li>
contains <a>
tag, now I want to add onClick event in every adding <a>
tag. 每个元素
<li>
包含<a>
标记,现在我想在每个添加的<a>
标记中添加onClick事件。 I try to do it so: 我尝试这样做:
liCode = '<li><a href="#">Text using variable foo: ' + foo + '</a></li>';
$('#list').append(function() {
return $(liCode).on('click', clickEventOccurs(foo));
});
In clickEventOccurs
I just output to console foo. 在
clickEventOccurs
我只是输出到控制台foo。 It works in strange way: this event performed just on init when every tag is adding to list, but after click on <a>
doesn`t perform anything. 它以一种奇怪的方式起作用:当每个标签都添加到列表中时,此事件仅在init上执行,但是单击
<a>
后不会执行任何操作。 How to make it works in proper way - on click performed code in clickEventOccurs? 如何使其以正确的方式工作-在clickEventOccurs中执行点击时执行的代码?
Firstly, you are assigning not a callback function, but a result of function evaluation. 首先,您分配的不是回调函数,而是函数求值的结果。 In right way it should be like this:
以正确的方式应该是这样的:
$('#list').append(function() {
return $(liCode).click(function() {
clickEventOccurs(foo);
});
});
Also, as you are using jQuery you might use benefits of events delegation and use .on
method this way: 另外,当您使用jQuery时,您可能会使用事件委托的好处,并通过以下方式使用
.on
方法:
$('#list').on('click', 'li', function() {
return clickEventOccurs(foo);
});
http://jsfiddle.net/lnplnp/uGJnc/ http://jsfiddle.net/lnplnp/uGJnc/
HTML : HTML:
<ol id="list">
<li><a href="#">Text using variable foo: foovalue</a></li>
</ol>
JAVASCRIPT/JQUERY : JAVASCRIPT / JQUERY:
function appending(foo) {
liCode = '<li><a href="#">Text using variable foo: ' + foo + '</a></li>';
$('#list').append($(liCode));
}
$('#list').on('click', 'li', function() {
return clickEventOccurs($("a", this).text());
});
function clickEventOccurs(v){
console.log(v.split(":")[1].trim());
}
appending("foo1");
appending("foo2");
appending("foo3");
To pass a variable to that function you'll have to make a second anonymous one, otherwise your clickEventOccurs function will be called at assignment, not as a callback. 要将变量传递给该函数,您必须创建另一个匿名函数,否则您的clickEventOccurs函数将在分配时被调用,而不是作为回调。
$('#list').append(function() {
return $(liCode).click(function() {
clickEventOccurs(foo)
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.