jQuery无法在按钮旁边获取文本区域

问题描述 投票:0回答:1

我正在尝试获取按钮旁边的文本区域的值,并且每次都只返回undefined

脚本:

 $('#comments-container').on('click', '#edit-comment-btn', (e) => {
        e.preventDefault();
        e.stopImmediatePropagation();

        var commentId = $(this).parent().find('textarea:nth-child(2)').val();
        var commentText = $(this).parent().find('textarea:nth-child(3)').val();
        alert(commentId);
        return;   //for testing. always returns undefined for some reason

        $.get('/openEditComment', {commentId: commentId, commentText: commentText, openCommentEditJs: true}, (data) => {
            $(this).parent().replaceWith(data);

        })
    })

视图:

{{#if userOwnsComment}}
    <div class="p-2">
        <form id="deleteCommentForm" name="deleteCommentForm" method="GET" action="/deleteComment">
            <button id="delete-comment-btn" name="delete-comment-btn" class="btn btn-outline-danger">Delete</button>
            <textarea readonly="readonly" id="commentId" name="commentId" style="display: none;">{{_id}}</textarea>
        </form>
    </div>
     <div class="p-2">
         {{#if openEditComment}}
            <form id="submitEditCommentForm" name="submitEditCommentForm" method="GET" action="/submitEditComment">
                <textarea class='text-submission' id='editCommentInput' name='editCommentInput' placeholder='Edit Comment' style='width: 100%; max-width: 100%;' rows='1'>{{text}}</textarea>
                <button id="submit-edit-comment-btn" name="submit-edit-comment-btn" class="btn btn-danger">Save</button>
                <textarea readonly="readonly" id="commentId" name="commentId" style="display: none;">{{_id}}</textarea>
            </form>
        {{else}}
            <form id="editCommentForm" name="editCommentForm" method="GET" action="/openEditComment">
                <button id="edit-comment-btn" name="edit-comment-btn" class="btn btn-outline-danger">Edit</button>
                <textarea readonly="readonly" id="commentId" name="commentId" style="display: none;">{{_id}}</textarea>
                <textarea readonly="readonly" id="commentText" name="commentText" style="display: none;">{{text}}</textarea>
            </form>
        {{/if}}
    </div>
    {{/if}}

我已经尝试通过$(this).next().find('textarea').eq(0);获取值,但还是没有。

javascript html jquery handlebars.js
1个回答
0
投票

只需尝试一下:

var commentId = $(this).next("textarea").attr("id");
var commentText = $(this).next("textarea").val();
© www.soinside.com 2019 - 2024. All rights reserved.