我想在同一个 div
中找到与另一个 class
相对应的 class
。
HTML 结构:
<div class="main">
<div class="party">
<a href="#"><img id="1001" class="vote" src="http://img2.jpg"></a>
<p class="votenums"> 20 votes.</p>
</div>
<div class="party">
<a href="#"><img id="1001" class="vote" src="http://imgtwo2.jpg"></a>
<p class="votenums"> 30 votes.</p>
</div>
jQuery 代码是:
$(function() {
$(".vote").live("click", function(e) {
e.preventDefault();
$(this).find(".votenums").text("changed text");
});
});
当我点击类vote
的img时,我想编辑类votenums
,对应于同一个div。
意思是,期望的行为是,当单击图像时,文本应该改变。
fiddle 在这里:http://jsfiddle.net/85vMX/1/
最佳答案
find
向下搜索,并且 .votenums
不是 .vote
的后代,您应该向上遍历到 div
然后找到后代 .votenums
$(function() {
$(".vote").live("click", function(e) {
e.preventDefault();
$(this).closest('div').find(".votenums").text("changed text");
});
});
如果您想要的 div 始终包含 class=party
,您可以通过它进行搜索:
$(this).closest('.party').find(".votenums").text("更改后的文本");
类选择器比元素选择器更好
查找:
Description: Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
最近:
Description: Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
关于jquery - 使用 jquery 在同一 div 中查找类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9147750/