用jQuery选择最近的DOM元素

用jQuery选择最近的DOM元素

本文介绍了用jQuery选择最近的DOM元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用jQuery在DOM相同级别的特定类中访问div?我已经尝试过.closest(),但是找不到该元素.

How to access the div with specific class that is on the same level of DOM using jQuery?I've tried .closest() but it doesn't find the element.

例如:

<!-- foreach loop starts { -->
<fieldset>
    <legend>Values</legend>
    <div class="characteristic-values">
        <!-- many divs inside -->
    </div>
    <input type="button" class="add-charactersitic-value" value="Add Value" />
</fieldset>
<!-- } foreach loop ends -->

和试图访问字符值"但未成功的JavaScript:

And JavaScript that tries to access the "charactersitic-values" but without success:

<script>
$(".add-charactersitic-value").live("click", function () {
    var addButton = $(this);

    // How to access the specified div from "addButton" variable?
    // This doesn't work:
    //addButton.closest(".characteristic-values").append("<b>somedata</b>");
});
</script>

在这种情况下如何访问特征值"?

How to access the "characteristic-values" in this case?

谢谢.

推荐答案

.prev('.characteristic-values');

.prev选择以前的 兄弟姐妹 . .closest选择 父母 (以及当前项目本身)

.prev selects previous siblings. .closest selects parents (and the current item itself)

如果该项不是前一个同级项,则此项将不起作用(因为.prev仅选择该元素).您可以改用以下任一方法:

If the item is not the immediate previous sibling, this won't work (as .prev only selects that one element). You can do either of these instead:

.prevAll('.characteristic-values');
.parent().find('.characteristic-values');

这篇关于用jQuery选择最近的DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:28