2013-04-28 106 views
0

我有这样的代码jQuery的点击功能不工作当点击图像

$("div").click(function() { 
    var CurrId = $(this).attr('id'); 
    if (CurrId == "First") { 
     $("#MenuContent").empty(); 
     $("#MenuContent").hide(); 
     $('<img src="images/End_05.png" width="30" height="30" /> <a id="First" class style="text-decoration:none;color:black">any </a>').appendTo("#MenuContent"); 
     $("#MenuContent").show("slow"); 
    } 
}); 

即当我点击div的图像(假设它的名字是mm)和链接出现。现在,我写了这个:

$("img").click(function() { 
    alert('yes'); 
}); 

当我点击图像显示(即mm)什么都没有。有任何想法吗?

回答

4

$('img')没有考虑它被调用后创建的元素。您必须使用事件代表来解释它们:

$('#MenuContent').on('click', 'img', function() { 
    alert('yes'); 
}); 
+0

感谢您的答复。 – 2013-04-28 06:45:55

1

可能是在图像实际添加之前调用第二个函数。尝试使用
jquery.live();jQuery.on()jQuery.delegate() 不是 click()

注意:jQuery.live()已被弃用。

+0

thnaks +1为你的好提示。 – 2013-04-28 06:46:31