[英]jquery does not detect click on child element
I have created a div element which is supposed to be a contact list. 我创建了一个div元素,它应该是一个联系人列表。 It should contain other divs in it.
它应该包含其他div。 What I'm trying to do, is attach a click handler on each list item (on each inner div).
我正在尝试做的是在每个列表项(每个内部div)上附加一个单击处理程序。 But the click handler is never triggered.
但是从不触发点击处理程序。
$(".contact").on("click", function() { alert("clicked"); });
.contacts { position: absolute; top: 10px; left: 300px; width: 100px; height: 250px; border-color: black; border-style: solid; z-index: 1; overflow: scroll; } .contact { position: relative; width: 80%; height: 20%; border-style: solid; border-color: red; z-index: 100; }
<div id="contactList" class="contacts"> <div id="1" class="contact">one</div> <div id="2" class="contact">two</div> <div id="3" class="contact">three</div> </div>
If I attach a click handler for the parent DOM object, it gets triggered. 如果我为父DOM对象附加了一个单击处理程序,它就会被触发。 Am I missing something here?
我在这里错过了什么吗?
EDIT: 编辑:
silly of me, i forgot to mention that children are added this way: 我很傻,我忘了提到孩子们这样添加:
$(".contacts").append($("<div id='"+id+"' class=contact >"+d[contact].name+"</div>"));
where "d" and "id" variables come from a successful server call. 其中“d”和“id”变量来自成功的服务器调用。
you have 你有
$(".contact").on("click",function(){
instead of 代替
$(".contacts").on("click",function(){
do you have this on trigger in the document is loaded event? 你在文件加载事件中有触发器吗? it won't work otherwise
它不会起作用
$(function(){
$(".contact").on("click",function(){
alert("clicked");
});
});
Edit: 编辑:
Since the OP forgot to mention something critical, here is my answer to that. 由于OP忘了提到一些关键的东西,这是我对此的回答。
There are no ' around the classname. 没有'围绕班级名称。 This should work:
这应该工作:
$(".contacts").append($("<div id='"+id+"' class='contact' >"+d[contact].name+"</div>"));
Edit 2 编辑2
You could also use the children() method: 你也可以使用children()方法:
$(function(){
$(".contacts").children("div").on("click",function(){
alert("clicked");
});
});
A slightly better way of putting this event on is in a document ready function that gets loaded with the page combined with using the .click jquery function. 放置此事件的稍微好一点的方法是在文档就绪函数中加载页面并结合使用.click jquery函数。 This is short hand for .on("click", FUNCTION).
这是.on(“点击”,FUNCTION)的简写。
Example: 例:
$(document).ready(function(){
$(".contact").click(function(){
alert("clicked");
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.