选择最近的textarea到一个按钮

Sam*_*ndy 2 javascript php jquery closest

我有一个td包含一个textarea和一个按钮的表,我想通过AJAX按钮点击发送textarea的值但是选择最近的textarea到按钮有问题.

JavaScript的

$(document).ready(function () {
    $(document).on("click", ".addR", function () {
        paperID = $(this).attr("paperID");
        commentID = $(this).attr("commentID");
        text = $(this).closest("textarea").val();
        $.ajax({
            data: {
                paperID: paperID,
                commentID: commentID,
                text: text
            },
            type: 'POST',
            url: 'add_rebuttal.php',
            success: function (response) {
                alert(response);
                window.location.href = window.location.href;
            }
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

PHP:

while ($row = mysql_fetch_assoc($comments)) {
    echo "<tr><td>{$row['text']}</td>";
?>
    <td><br /><textarea class="reText" rows='5' name='reText' id='reText' style='width:98%;' type='text'></textarea>
    <button commentID="<?php echo $row['comment_id'] ?>" paperID="<?php echo $paper_id ?>" class="addR" type="button" name="addR" id="addR">send rebuttal</button></td></tr> <?
}
Run Code Online (Sandbox Code Playgroud)

问题是$(this).closest("textarea").val();返回undefined,那么我怎么能解决这个问题呢?

Sco*_*tty 6

nearest()返回最近的祖先.你的textarea不是你按钮的祖先,它是以前的兄弟姐妹.相反,尝试:

text = $("textarea", $(this).parent()).val();
Run Code Online (Sandbox Code Playgroud)