jQuery获取点击后的下一个隐藏值的兄弟元素

3

我正在尝试在链接的点击事件中获取隐藏字段的值。这是这些元素所在的位置:

<p>
    <a class="showCommentAttachment cboxElement" href="#">Attachments</a>
    <input type="hidden" value="13" id="ctl00_ContentPlaceHolder1_lvComment_ctrl3_hfCommentId" name="ctl00$ContentPlaceHolder1$lvComment$ctrl3$hfCommentId">
</p>

以下是完整的标记:

<div id="divComment" class="comment-text">
    <div class="comment-author">
         David Chart
    </div>
    <span class="comment-date-time">Sep 29, 2011 08:12:42 PM</span>
    <p>
         Some comment text goes here. Some comment text goes here.

    </p>
    <p>
        <a class="showCommentAttachment cboxElement" href="#">Attachments</a>
        <input type="hidden" value="13" id="ctl00_ContentPlaceHolder1_lvComment_ctrl3_hfCommentId" name="ctl00$ContentPlaceHolder1$lvComment$ctrl3$hfCommentId">
    </p>
</div>

以下是 jQuery 代码:

$("#divComment a.showCommentAttachment").click(function() {

    var nextSibling = $(this).next().find('input:hidden').val();

    $("#showCommentId").html(nextSibling + "<-- Here's the comment ID ");

 });

我从nextSibling得到的是未定义的。我试过使用nexAll,像这样:

var nextSibling = $(this).nextAll().find('input:hidden').val();

仍然得到了未定义。

谢谢。

3个回答

8
由于下一个元素肯定是隐藏输入框,因此您应该简单地使用 $(this).next()。另外,使用 $(this).next().find() 将查询隐藏输入元素的子元素。这是来自 jQuery API 文档 的说明:

.find()

获取当前匹配元素集合中每个元素的后代元素,通过选择器、jQuery 对象或元素进行筛选。

所以您需要使用 $(this).next().val()

3

.next() 方法返回的是下一个兄弟元素,而在这里它就是输入框本身。调用 .find() 方法会查找该元素的后代元素(但是在这里没有)。

你只需要使用 $(this).next().val() 就可以了。


0

请尝试:

$(this).next().val();

或者

$("#divComment a.showCommentAttachment").next().val();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接