我有一个按钮可以在PHP功能内调用javascript函数:
<button id="upvoteCommentButt"'.$rowNr.'" class="btn btn-primary btn-sm" onclick="upvoteComment(\''.$commentID.'\', \''.$rowNr.'\')">
这是Chrome控制台显示一个innerHTML空错误的代码行:
echo '<span class="p" id="commentVotesTxt"'.$rowNr.'> '.$commentVotes.' </span>';
注意:
$rownNr
已被php代码成功检索,控制台将其打印出来,因此我确定以下JS函数可以正确获取它:function upvoteComment(commentID, rowNr) {
var rowNr = rowNr;
$.ajax({
url:"vote-comment.php?isUpvoted=true&commentID=" + commentID,
type: "GET",
success:function(data) {
var results = data;
console.debug(results);
document.getElementById("debug").innerHTML = 'VOTES: ' + results + ' -- rowNr: ' + rowNr;
// Show updated votes
console.debug("ROW NR: " + rowNr);
document.getElementById("commentVotesTxt" + rowNr).innerHTML = " " + results + " ";
// Change buttons style
$( "#upvoteCommentButt" + rowNr ).removeClass( "btn-default" ).addClass( "btn-primary" );
$( "#downvoteCommentButt" + rowNr ).removeClass( "btn-primary" ).addClass( "btn-default" );
}, error: function (xhr) {
document.getElementById("debug").innerHTML = xhr.status;
if(xhr.status == 418){
document.getElementById("errorMessage").innerHTML = "<strong>You already upvoted this comment</strong>";
document.getElementById("errorAlert").style.display = 'block';
} else if (xhr.status == 417){
document.getElementById("errorMessage").innerHTML = "<strong>You cannot vote your own comments!</strong>";
document.getElementById("errorAlert").style.display = 'block';
}
// hide errorAlert
$("#errorAlert").fadeTo(2000, 500).slideUp(500, function(){
$("#errorAlert").slideUp(500);
document.getElementById("errorMessage").innerHTML = "";
});
}
});
}
当我单击
upvoteCommentButt
时,该函数调用PHP脚本并成功执行查询,但是当要更改innerHTML
标记的commentVotesTxt
号时,它会输出以下错误:我究竟做错了什么?
谢谢!
最佳答案
这看起来不对。您已将"
的结束ID
放在$rowNr
之前。因此,所有span
都具有相同的id
“commentVotesTxt”。
echo '<span class="p" id="commentVotesTxt"'.$rowNr.'> '.$commentVotes.' </span>';
它应该像
echo '<span class="p" id="commentVotesTxt'.$rowNr.'"> '.$commentVotes.' </span>';