我正在尝试编写一个函数,当您单击按钮时,该函数将动态显示表单(在div中,其中将有多个实例,因此会有奇怪的“ id”名称)。然后,它应该发布到单独的PHP文件。这是我到目前为止的代码:

function add_comment_url($table, $id) {
    $html = '<div id="comment' . $id . '" name="comment_box" style="display: none">
        <form action="cgi-bin/add_comment.php" method="post">
            <textarea id="comment" name="comment"></textarea>
            <input type="hidden" name="id" value="' . $id . '">
            <input type="hidden" name="table" value="' . $table . '">
            <input type="submit" name="submit" value="Submit Comment">
        </form></div>
        <input type="button" value="Add Comment" onclick="showComment();">
        <script>
    var id= ' . json_encode($id) . ';
    showComment(id);
    </script>';

    return($html);
}


“添加评论”按钮显示正常,但我无法显示,并且当我单击该按钮时,Firefox控制台显示“ TypeError:div is null”错误。

我猜想我搞砸了JS变量赋值,但是我对如何解决这个问题不知所措。有什么想法吗?

编辑-最终代码

我弄清楚了我做错了什么...在不需要时定义了var!这是新功能,可以正常工作:

function add_comment_url($table, $id) {
$html = '<div id="comment' . $id . '" name="comment_box" style="display: none">
    <form action="cgi-bin/add_comment.php" method="post">
        <textarea id="comment" name="comment"></textarea>
        <input type="hidden" name="id" value="' . $id . '">
        <input type="hidden" name="table" value="' . $table . '">
        <input type="submit" name="submit" value="Submit Comment">
    </form></div>
    <input type="button" value="Add Comment" onclick="showComment(' . $id . ');">';

return($html);


}

最佳答案

您不能在PHP字符串中使用<?php。您应该使用字符串串联或插值:

function add_comment_url($table, $id) {
    $html = '<div id="comment' . $id . '" name="comment_box" style="display: none">
        <form action="cgi-bin/add_comment.php" method="post">
            <textarea id="comment" name="comment"></textarea>
            <input type="hidden" name="id" value="' . $id . '">
            <input type="hidden" name="table" value="' . $table . '">
            <input type="submit" name="submit" value="Submit Comment">
        </form></div>
        <input type="button" value="Add Comment" onclick="showComment();">
        <script>
        function showComment() {
        var id= ' . json_encode($id) . ';
        div = document.getElementById(\'comment\' + id);
        div.style.display = "block";}</script>';
    return($html);
}


您是否为每个注释块重复此函数定义?我建议只定义一次showComment(),并使其以commentID作为参数。

关于php - 传递PHP变量时,JavaScript抛出TypeError,document.getElementById,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18571461/

10-10 21:45
查看更多