Javascript在传递PHP变量时抛出TypeError,document.getElementById

时间:2013-09-02 10:52:26

标签: php javascript html variables

我正在尝试编写一个动态显示一个表单的函数(在div中,当你点击一个按钮时会有几个实例,因此有一个奇怪的“id”名称)。然后,它应该POST到一个单独的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);

}

1 个答案:

答案 0 :(得分:4)

您不能在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作为参数。