从指定元素中选择父元素。
如何从按钮中精确选择class="bt-add-com"
到带有jquery选择器的上述父元素class="new-com-bt"
?
<form action="" method="POST" class="post_id">
<div class="new-com-bt" >
<span>Write a comment ...</span>
</div>
<div class="new-com-cnt" >
<textarea class="the-new-com"></textarea>
<button class="bt-add-com">Post comment</button>
<button class="bt-cancel-com">Cancel</button>
</div>
</form>
答案 0 :(得分:0)
$('.the-new-com')
.parent() // get parent
.prev('.new-com-bt') // get previous element only if having the class
.css('color', 'red');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="" method="POST" class="post_id">
<div class="new-com-bt">
<span>Write a comment ...</span>
</div>
<div class="new-com-cnt">
<textarea class="the-new-com"></textarea>
<button class="bt-add-com">Post comment</button>
<button class="bt-cancel-com">Cancel</button>
</div>
</form>
&#13;
答案 1 :(得分:0)
首先,具有类“new-com-bt”的元素不是具有类“bt-add-com”的按钮的父元素。更像是叔叔。
另外,到目前为止你做了什么?
无论如何,试试:
$(".bt-add-com").click(function(){
var elem = $(this).closest(".new-com-bt");
});