【问题标题】:jQuery addclass to each Wordpress post imagejQuery addclass 到每个 Wordpress 帖子图像
【发布时间】:2010-08-21 07:29:45
【问题描述】:

这是我目前所拥有的:

<script>
$(document).ready(function(){
    $(".entry-content img:first").addClass('postimage');
});
</script>

如您所见,对于 .entry-content 的第一张图片,它添加了我的类。酷,这很好用。不酷,它不适用于每个帖子,而只适用于页面上的第一个。

我不确定如何解决这个问题。我需要以某种方式使用 .each 还是我已经拥有的有什么问题?

谢谢

【问题讨论】:

  • 你能给我们看看你的标记吗?

标签: javascript jquery css wordpress


【解决方案1】:

这是因为 CSS 选择器选择的是第一个 .entry-content img,而不是每个 .entry-content 中的第一个 img。这是关于运算符优先级的。

不过,您可以遍历每个 .entry-content 并在该节点中手动选择 img:first

$(document).ready(function(){
    var entries = document.querySelectorAll('.entry-content');
    for (var i = 0; i < entries.length; i++) {
        var firstImage = $(entries[i].querySelectorAll('img:first')[0]);
        firstImage.addClass('postImage');
    }
});

【讨论】:

  • 所以应该是 $("img:first .entry-content") ?
  • 没有。这将选择第一个img 中的所有.entry-content 节点。实际上,我不确定您是否可以将:first 放在那里。您需要做的是选择.entry-content。然后循环遍历其中的每一个并选择其中的img:first
  • 我只是不确定如何选择条目内容,然后为每个实例选择 img:first?这是 jq 中的另一行吗?
  • 我已经编辑了我的帖子以包含一些可能对您有用的代码。
  • -1 querySelectorAll 尚未在所有 A 级浏览器中实现。
【解决方案2】:

这将遍历您的所有帖子并将该类应用于每个帖子中的第一张图片。

$.each('.entry-content', function() {
    $(this).find('img:first').addClass('postImage');
});

【讨论】:

    【解决方案3】:

    Paul Dragoonis 答案的变体:

    $(".entry-content").each(function ()
    {
        $("img:first", this).addClass("postImage");
    });
    

    【讨论】:

      猜你喜欢
      • 2012-08-01
      • 2012-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-30
      • 1970-01-01
      • 2019-04-06
      • 1970-01-01
      相关资源
      最近更新 更多