问题
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.
For example:
<!-- 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 -->
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?
Thank you.
回答1:
.prev('.characteristic-values');
.prev
selects previous siblings. .closest
selects parents (and the current item itself)
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');
回答2:
$(".add-charactersitic-value").prev(".characteristic-values");
http://jsfiddle.net/UUdXk/
来源:https://stackoverflow.com/questions/6476762/select-the-nearest-dom-element-with-jquery