我目前在使用C#Web应用程序时遇到问题。这是我的JavaScript:
$(document).ready(function () {
$("#submitComment").click(function () {
$.post("/Home/Index", { "CommentText": $("#CommentText").val() }, function (Comment) {
for (var index = 0; index < Comment.length; index++) {
var dateObject = eval('new' + Comment[index].CommentDate.replace(/\//g, ' '));
Comment[index].CommentDate = cleanDate(dateObject);
}
$("#commentList li").not("li:last").replaceWith($("#commentTemplate").tmpl(Comment));
for (var newIndex = 0; newIndex < Comment.length; newIndex++) {
addLikeToComment(Comment[newIndex].ID);
}
});
});
function cleanDate(dateObject) {
var Month = dateObject.getMonth();
var Day = dateObject.getDate();
var month = new Array("Janúar", "Febrúar", "Mars", "Apríl", "Maí", "Júní", "Júlí", "Ágúst", "September", "Október", "Nóvember", "Desember");
var Hour = dateObject.getHours();
var Minute = dateObject.getMinutes();
if (Hour < 10)
Hour = "0" + Hour;
if (Minute < 10)
Minute = "0" + Minute;
var dateString = (Day + ". " + month[Month] + " " + Hour + ":" + Minute);
return dateString;
}
function addLikeToComment(ID) {
$.get("Home/GetLikeByID/" + ID, "", function (Likes) {
if (Likes.length != 0) {
var selector = "div #" + ID;
$("#likeTemplate").tmpl(Likes).appendTo($(selector));
}
});
}
$("#commentList li div.commentBody div a").click(function (event) {
var id = $(this).find("span").html();
id = id.replace(/^\s+|\s+$/g, "");
$.post("/Home/AddLike/" + id, "", function (LikeList) {
if (LikeList.length != 0 || LikeList[0].UserName != "") {
var selector = "div #" + id;
$(selector).empty();
$("#likeTemplate").tmpl(LikeList).appendTo($(selector));
}
});
event.preventDefault();
});});
模板:
<script id="commentTemplate" type="text/html">
<li>
<a href="http://www.ru.is"><img src='<%= Url.Content("~/Images/User.png") %>' alt="Notandi" /></a>
<div class="commentBody">
<a href="http://www.ru.is">${UserName}</a>
<span>${CommentText}</span>
<div>
<abbr title='${CommentDate}'>${CommentDate}</abbr>
<a href="#"><span style="display:none;"> ${ID} </span>Líkar þetta</a>
<div id="${ID}" class="likeList">
</div>
</div>
</div>
</li>
</script>
<script id="likeTemplate" type="text/html">
<p class="likeLook"> ${UserName} Líkar þetta.</p>
</script>
两者都独立工作,但如果我点击“#submitComment”,然后点击“#commentList li div.commentBody div a”那么该事件不会触发,即我可以创建评论但之后我不能“喜欢“任何东西。有谁知道问题是什么?
答案 0 :(得分:1)
很难准确地说出来,但在我看来,就像你在#commentList
的回调上操纵$.post
一样。如果是这种情况,那么你可能只是丢失了对象本身的点击处理程序。
一个简单的测试就是改变
$("#commentList li div.commentBody div a").click(function(event){...
到
$("#commentList li div.commentBody div a").live('click',function(event){...