我正在尝试在我网站上的一堆链接中创建一个事件监听器。这些链接是在循环中生成的,所以我最终得到<a class = "replyButton" id = "replyID"<? echo $x; ?>
等。
我正在尝试使用下面的代码在点击每个相应的链接时显示一个输入框,但没有运气。在一种情况下,我也可以使用普通的JS来使用它,但不使用JQuery,在这样的几个外推。任何帮助都会非常棒。
window.onload = function(){
$('.replyButton').each(function(index){
var domElementId = "replyArea" + index;
domElementId.onclick = function() {
var replyFieldHtml = '<div class = "span4" id = "replyTextField"><table><tr><td id = "replyPhoto"><img src = "/assets/img/usr/profile_holder.jpg" /></td><td id = "replyContent"><input type = "text" id = "replyInput" onkeydown="if (event.keyCode == 13) wallReply()" placeholder = "leave a reply..." /></td></tr></table></div>';
document.getElementById('domElementId').innerHTML = replyFieldHtml;
console.log('domElementId');
return false;
}
});
}
编辑:这是我用来生成html的循环... $ x = 0; while($ x&lt; 8){ $ X ++; $ r = $ wallarray - $ x;
$postContent = $wall_content['wall_posts'][$x-1];
$postUser = getUserNameById($wall_content['userID'][$x-1]);
?>
<div class = "row">
<div class = "span6">
<div class = "span1" id = "wallPhoto"><img src ="assets/img/usr/profile_holder.jpg></div>
<div class = "span4">
<div class = "span4" id = "wallFeedStyle"><a id = "wallUserLink" href = "#"><b><? echo $postUser; ?></b></a></div>
<div class = "row">
<div class = "span5">
<div class = "span4" id = "userPost"><? echo $postContent; ?></br><p class = "wallsmall"><a href="#" id = "postLike"></i>Like</a> ·<a class = "replyButton" id = "replyButton<? echo $x; ?>" href="#"></i>Reply</a></p></div></div>
</div>
<div class = "row">
<div class = "span5">
</div>
</div>
<div class = "row" id = "replyArea<? echo $x; ?>"></div>
</div>
<?
}
?>
答案 0 :(得分:4)
您以错误的方式使用变量。试试这个:
window.onload = function () {
$('.replyButton').each(function (index) {
var domElementId = "replyArea" + index;
$('#' + domElementId).on('click', function () {
var replyFieldHtml = '<div class = "span4" id = "replyTextField"><table><tr><td id = "replyPhoto"><img src = "/assets/img/usr/profile_holder.jpg" /></td><td id = "replyContent"><input type = "text" id = "replyInput" onkeydown="if (event.keyCode == 13) wallReply()" placeholder = "leave a reply..." /></td></tr></table></div>';
$(this).html(replyFieldHtml);
console.log(domElementId);
return false;
});
});
}
答案 1 :(得分:0)
在深入研究.on()和.bind()背后的历史后,我最终使用下面的代码来解决这个问题。谢谢你的帮助!
$('a.replyButton').on("click", function(){
var index = $(this).attr('id');
$('#replyArea'+index).html('<div class = "span4" id = "replyTextField"><table><tr><td id = "replyPhoto"><img src = "/assets/img/usr/profile_holder.jpg" /></td><td id = "replyContent"><input type = "text" id = "replyInput" onkeydown="if (event.keyCode == 13) wallReply()" placeholder = "leave a reply..." /></td></tr></table></div>');
});
我最终将“replyLink”ID属性更改为该数字。所以有一堆/<.a>使用class replyButton,将ID属性作为数字。它似乎很好地完成了工作,也没有必要设置.each()循环。