【问题标题】:target all parents(".class") of a specific class jquery针对特定类jquery的所有父母(“.class”)
【发布时间】:2013-06-20 18:30:15
【问题描述】:

我无法定位具有特定班级的所有家长。

如果我点击george michael,我想改变包含“michael”和“george sr”的<p>标签的颜色。

下面是 dummy html 和失败的 jQuery。

<ul>
<li><div class="leaf"><p>george sr</p></div>
<ul>
    <li><div class="leaf"><p>michael</p></div>
        <ul>
            <li><div class="leaf"><p>george michael</p></div></li>
        </ul>
    </li>
    <li><div class="leaf"><p>gob</p></div>
        <ul>
            <li><div class="leaf"><p>steve holt</p></div></li>
        </ul>
    </li>
    <li><div class="leaf"><p>lindsay</p></div>
        <ul>
            <li><div class="leaf"><p>maeby</p></div></li>
        </ul>
    </li>
</ul>

我尝试过:

$(document).on("click", '.leaf', function() {
   $(this).parents(".leaf").children('p').css('color','red');
});

编辑请求:还有,有人能解释一下为什么上面的 jquery 不起作用吗?

请帮忙:)

供您使用:http://jsfiddle.net/KuZrq/2/

【问题讨论】:

  • 您的代码不起作用,因为 leaf divs 不是彼此的祖先,它们是包含其他 leaf divuls 的兄弟姐妹s。如果您将leaf 类直接提供给lis,您的代码应该可以工作。

标签: jquery jquery-selectors parent


【解决方案1】:

像这样:

$(document).on("click", '.leaf', function () {
    $(this).closest('li').parents('li').find('> .leaf > p').css('color', 'red');
});

FIDDLE

【讨论】:

  • 你所做的工作,但我找到了一个更好的方法,我将使用它。谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-24
  • 1970-01-01
  • 2013-10-12
相关资源
最近更新 更多