[英]how to pass a variable function to an onclick event in javascript?
I am a newbie in javascript. 我是javascript的新手。 I am not sure what am I doing wrong here.
我不确定我在做什么错。 I want to pass in a variable which is a function to an onclick event of an anchor tag.I could not figure out.
我想将一个作为函数的变量传递给锚标记的onclick事件。 Thanks in advance.
提前致谢。
var test = function(val1, val2) { alert("bla"); };
$.each( result, function (key, value){ var a = key; var b = key+value; var doSomething = function() { test (a, b)); $('#id').bind("click", test); });
I need to create the anchor tags dynamically and pass multiple variables to "onclick" event. 我需要动态创建锚标记,并将多个变量传递给“ onclick”事件。 so what I am trying to do is create a variable function dynamically inside a for loop and bind it to an anchor tag
所以我想做的是在for循环内动态创建变量函数并将其绑定到锚标记
try this code: 试试这个代码:
var test = function() {
alert("hello");
};
$("#myUL").append("<li><a href='#' onclick=test()>test</a></li>");
Is what you want? 是你想要的吗?
You need something like this: 您需要这样的东西:
for (var i = 0; i < 5; i++) {
$("button").eq(i).on("click", {value: i}, function(event) {
var msgs = [
"button = " + $(this).index(),
"event.data.value = " + event.data.value,
"i = " + i
];
logDiv.append( msgs.join(", ") + "<br>" );
});
}
jQuery site: event.data jQuery站点: event.data
You should use : 您应该使用:
$(document).ready(function(){
$("#myUL").click(function(){
alert("hello");
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.