0

ボタンをクリックするとフォームを動的に表示する関数を作成しようとしています (div 内にいくつかのインスタンスがあるため、奇妙な "id" 名)。次に、別の PHP ファイルに POST する必要があります。これまでのコードは次のとおりです。

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);

}

4

1 に答える 1

4

<?phpPHP 文字列内では使用できません。文字列の連結または補間を使用する必要があります。

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

于 2013-09-02T10:55:09.597 に答える