[英]Why my find('a') doesn't work in jquery?
I have a function in jquery: 我在jquery中有一个函数:
function handleUpcomingUserTexts () { function handleUpcomingUserTexts(){
$.ajax({
url: 'getjson.php',
type: "POST",
data: {
mail: '<?php echo htmlentities($_SESSION["email"]); ?>'
},
dataType:'text',
success: function(ans)
{
var data = JSON.parse(ans);
$.each(data, function(i, v) {
var upcomingText = $('<a href="#" class="list-group-item"><i class="fa fa-comment fa-fw"></i> '+v.Content+'<span class="pull-right text-muted small"><em>'+v.Date+'</em></span></a>');
$('#upcomingTexts').append(upcomingText);
var a = upcomingText.find('a').on('click',function(e){
e.preventDefault();
alert("here");
});
});
}});
};
and it fills the html nicely, but when I click the link - nothing happens and I don't see the alert message. 它很好地填充了html,但当我点击链接时 - 没有任何反应,我没有看到警报消息。 What is wrong in here? 这里有什么问题?
Because upcomingText
is already a a
. 因为upcomingText
已经是a
。 And you are trying to find a a
in your a
. 而你正在努力寻找一个a
在你的a
。
You can just write this : 你可以这样写:
var a = upcomingText.on('click',function(e){
When you write var variable = $('<a ...>...</a>');
当你写var variable = $('<a ...>...</a>');
, the result is the root tag of the given html. ,结果是给定html的根标签。 So in your case, the <a>
. 所以在你的情况下, <a>
。
Because upcomingText
is <a>
and in this tag there are not any <a>
tags, so you need use upcomingText
like this 因为upcomingText
是<a>
并且在此标记中没有任何<a>
标记,所以你需要像这样使用upcomingText
upcomingText.on('click',function(e) {});
but event delegation
in this case better solution 但在这种情况下event delegation
更好的解决方案
// add this code before $.ajax
$('#upcomingTexts').on('click', 'a.list-group-item', function(e) {});
Try to use delegate
function, on #upcomingTexts
block 尝试在#upcomingTexts
块上使用delegate
函数
$('#upcomingTexts').delegate('a', 'click', function(e){
//your code here
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.