[英]How can I run element's click event handler?
HTML 的HTML
<div id="menu-left-left">
<ul>
</ul>
</div>
jQuery jQuery的
var temp = "";
for (var i = 0; i < 2; i += 2) {
temp += "<li> <a href='#' class='test'> + "Test" + </a> </li>";
}
$("#menu-left-left ul").html(temp);
$(".test").click(function() {
alert("Element test class");
});
I want to load #menu-left-left
element using jQuery. 我想使用jQuery加载#menu-left-left
元素。 When this code block works the menu seems to look like I want. 当此代码块工作时,菜单似乎看起来像我想要的。 But .test
element's click event handler doesn't work. 但是.test
元素的click事件处理程序不起作用。 How can I run this event handler? 如何运行此事件处理程序?
You don't need to delegate the events as you are selecting the element after adding it in. Your problem is that the body of your loop isn't valid. 在添加元素之后选择元素时,您无需委派事件。您的问题是循环的主体无效。
var temp = "";
for (var i = 0; i < 2; i += 2) {
temp += "<li> <a href='#' class='test'> + "Test" + </a> </li>";
}
There is a syntax error in your string concatenation. 字符串连接中存在语法错误。 You probably meant either: 您可能的意思是:
"<li> <a href='#' class='test'>" + Test + "</a> </li>" // Test is a variable
or 要么
"<li> <a href='#' class='test'>Test</a> </li>"
Here's a working version of your code: 这是您的代码的有效版本:
var temp = ""; for(var i=0; i<2; i+=2) { temp += "<li> <a href='#' class='test'> Test </a> </li>"; } $("#menu-left-left ul").html(temp); $(".test").click(function() { alert("Element test class"); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div id="menu-left-left"> <ul> </ul> </div>
You should use delegated events as the element you're targetting is added dynamically. 您应该使用委托事件,因为您要定位的元素是动态添加的。 Try this : 尝试这个 :
$("#menu-left-left ul").on("click","li a.test",function() {
alert("Element test class");
}); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.