传递给 Javascript 函数的变量不会改变


variable passing to Javascript function is not changing

我正在尝试实现一个报告网站上评论的功能。 我正在使用PDO并在PHP类中使用该功能。

单击"报告"时,将调用一个JS函数,该函数使用Ajax调用PHP函数,该函数将更新数据库/向管理员发送电子邮件。

我不明白为什么,但是传递给JS的id总是相同的。

我已经完成了各种输出来测试,并且在 HTML 中 id 是正确的。 目前我正在测试3种不同的。 当我在函数中提醒id时,它总是相同的。

任何帮助都非常感谢。

该 HTML:

<? foreach ($comments as $c){
   $commentId = $c['id']; ?>
     <p><a href="#" id="report" name="report" data-value="<?php echo $commentId ?>" onclick="reportComment(); return false;">Report?</a></p>
<? } ?>                 

JS:

function reportComment(){
var id = $('#report').attr('data-value');
var url = "/Perspect/commentsAjax/report.php";
var params = {id: id};
$.ajax({
    cache: false,
    type: 'POST',
    url: url,
    data:params,
    dataType:'json',
    success: function(){
        alert("sucess");
        //change ahref to say this comment has been reported
    },
    error: function(error){
        console.log(error);
    }
});
alert("ID" + id);
}

.PHP:

<?php include '../core/init.php';
if($_POST){
  $id = $_POST['id'];
  $articleComments->reportComment($id);
}
?>

问题是你所有的链接都共享同一个id="report",所以你无法访问其中一个(但JS会自动选择第一个出现)。这可以通过简单地将 id 作为参数传递来解决。

<p><a href="#" name="report" onclick="reportComment(<?php echo $commentId; ?>); return false;">Report?</a></p>
//...
function reportComment(id){

当你想在点击后操作元素时,你可以像下面这样做

<? foreach ($comments as $c){
   $commentId = $c['id']; ?>
     <p><a href="#" id="report_<?php echo $commentId ?>" name="report" onclick="reportComment(<?php echo $commentId ?>); return false;">Report?</a></p>
<? } ?>

现在你有唯一的 id report_1report_2 等,你的 JS 可能如下所示

function reportComment(id){
    //do your stuff
    $("#report_"+id).text("already reported");

正如您的问题评论中所建议的那样,这也只能使用JavaScript来解决(借助jQuery),您不需要HTML中的onclick逻辑

<a class="report" data-value="1">report</a>
<a class="report" data-value="2">report</a>

这可能是 JS

$(".report").click(function(){
    var id = $(this).attr('data-value');
    //do your magic
    $(this).text('already reported');
});