【问题标题】:Selector for a list-item containing a child element with a specified attribute value包含具有指定属性值的子元素的列表项的选择器
【发布时间】:2014-07-23 09:12:26
【问题描述】:

我正在尝试根据 <a> 标记中的特定 href 值在列表中显示特定项目。

 <ul id="images">
    <li class="other-image" style="display: none;">
        <a target="_blank" href="http://www.example.com/page.html">
            <img src="http://www.test.com/home/pic.jpg">
        </a>
    </li>
    <li class="other-image" style="display: none;">
        <a target="_blank" href="http://www.exmaple.com/index.html">
            <img src="http://www.example-image.com/image.jpg">
        </a>
    </li>
    <li class="other-image" style="display: none;">
        <a target="_blank" href="http://www.example1.com/test">
            <img src="http://www.example-image1.com/image1.jpg">
        </a>
    </li>
</ul>

$(document).ready(function () {
    $("#images").find("li").fadeIn().delay(10000).fadeOut();
});

例如,我想显示href="http://www.exmaple.com/index.html" 所在的项目。我不想改用索引,因为随着从列表中添加/删除更多项目,该项目可能具有不同的索引。我尝试了几种不同的方式(如下)编写选择器,以仅选择具有此特定 href 值的列表项,但没有成功。

尝试 #1:

$("#images").find("li").filter($("a[href='http://www.exmaple.com/index.html']")).fadeIn().delay(10000).fadeOut();

尝试 #2:

$("#CCCImages").find($("a[href='http://www.exmaple.com/index.html']")).fadeIn().delay(10000).fadeOut();

尝试 #3:

$("#CCCImages").children($("a[href='http://www.exmaple.com/index.html']")).fadeIn().delay(10000).fadeOut();

任何建议将不胜感激。

【问题讨论】:

  • +1 表示作为新用户并在询问之前先尝试自己解决问题

标签: javascript jquery jquery-selectors


【解决方案1】:

尝试 1 失败,因为您正在 lis 列表中查找锚标记。它不是在看孩子们。

尝试 2 失败,因为你没有褪色

尝试3,anchor不是孩子。

有很多方法可以做到。

一个是

$("a[href='http://www.exmaple.com/index.html']").closest("li").fadeIn();

【讨论】:

  • 如果你想从另一个方向做。你想使用.has()
【解决方案2】:

在使用 jQuery 选择器时,特别是在调用 [DOM 遍历] 方法之后,在调用 jQuery 对象上的方法时必须注意当前匹配集。例如,打破你的第一次尝试,

$("#images")   // Targeted set is only the <ul>
  .find("li")  // Only the 3 <li> elements
  .filter($("a[href='http://www.exmaple.com/index.html']")) // matches nothing.
  .fadeIn()
  .delay(10000)
  .fadeOut();

filter 检查每个&lt;li&gt; 并检查它是否也是&lt;a&gt;,因此它们都失败并被排除在外。正如文档指出的那样:

提供的选择器针对每个元素进行测试;所有匹配选择器的元素都将包含在结果中。

调整以上内容,我们可以轻松地修正过滤器,使其更有效。首先,定位想要的&lt;li&gt;s:$("#images li")

然后使用has 过滤结果,将您的结果集限制为具有与您的标准匹配的锚链接的结果集:.has("a[href='http://www.exmaple.com/index.html']")

最后,做你的褪色。

$("#images li")
  .has("a[href='http://www.exmaple.com/index.html']")
  .fadeIn()
  .delay(10000)
  .fadeOut();

当然,如果您好奇,也可以利用filter 方法以一种有用的方式来完成此任务。该方法有一个重载变体,它接受用于过滤的函数。在这种情况下,下面的用法在功能上等同于使用has,但更加冗长。

$("#images li").filter(function() {
    return $(this)
             .find("a[href='http://www.exmaple.com/index.html']")
             .length > 0;
})
.fadeIn(); // etc.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    • 2016-02-03
    • 2014-07-06
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多