选择离按钮最近的文本区域

select the closest textarea to a button

本文关键字:文本 区域 最近 按钮 选择      更新时间:2023-09-26

我有一个表td,其中包含一个textarea和一个按钮,我想通过AJAX在按钮点击时发送文本区域的值,但选择离按钮最近的文本区域时出现问题。

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

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> <?
}

问题是$(this).closest("textarea").val();返回未定义,那么我如何解决这个问题?

closest()返回最近的祖先。您的文本区域不是按钮的祖先,而是以前的兄弟区域。相反,请尝试:

text = $("textarea", $(this).parent()).val();

要获取文本区域的文本,必须使用text()而不是val()。正如Scotty所指出的,你想要的文本区域不是祖先,所以不要使用closest()