jquery - 使用 jquery 在同一 div 中查找类

标签 jquery jquery-selectors

我想在同一个 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("更改后的文本");
类选择器比元素选择器更好

JSFiddle DEMO

查找:

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/

相关文章:

javascript - 文档就绪后提交时的绑定(bind)函数

jquery - JSP网站的图像编辑器

javascript - jQuery 表单选择器 :input is excluding the :checked in chrome and firefox

javascript - 使用 jQuery 计算直接子 div 元素

php - yii 中的 ajax 调用 Controller (javascript)

javascript - 使用 jQuery 向页面动态添加脚本从不使用缓存文件

javascript - jQuery 选择器 "memory"

JQuery + SVG 对象 : Capture click event properly

jquery 正则表达式选择器