使用jQuery更改元素的背景图像是不会的

时间:2013-08-26 17:44:23

标签: jquery css background-image

我正在使用以下代码示例的组合来更改background-image css值,具体取决于单独的元素是否包含文本字符串。

单独的元素多次出现在页面上(wordpress post meta data),因此每次满足条件时都应运行此jQuery。

$(window).load(function(){
if ($(".postmetadata").contains("Seattle")) {
        $(this).closest(".boxy").find(".storyNoIMG")
        .addClass('.seattleIMG');
    } else {
    }
});

这是我正在使用的第二个例子:

            var imageURL = "images/seattle.png";

            if ($(".postmetadata").contains("Seattle")) {
                $(this).closest(".boxy").find(".storyNoIMG")
                .css("background-image","url(" + "images/seattle.png" + ")");
            }

这是html上下文:

        <div class="boxy">
            <div class="boxGrad">

                <div class="postmetadata">
                    <?php echo time_ago(); ?> •
                    <?php the_category(' • ') ?>
                </div>
                <div class="articleTitle">
                    <a><?php the_title(); ?></a>
                </div>
                <div class="exPand">
                </div>
            <div class="rightCtrls">

                <!-- heart + -->
                <?php echo getPostLikeLink(get_the_ID());?>
                    <div  class="imageGlass">
                        <a href="#">
                            <img src="<?php echo get_template_directory_uri(); ?>/media/imageMag-02.png">
                        </a>
                    </div>
                </div>

            </div> <!-- end post right controls -->                 
                <div class="ajaxBoxLoadSource">
                    <iframe class="ajaxIframe"></iframe>
                </div>
                <div class="storyNoImg"></div>
            <div class="articleImageThumb">
                <a href="<?php if(get_post_meta($post->ID, "url", true)) echo get_post_meta($post->ID, "url", true); else the_permalink(); ?>" rel="<?php the_ID(); ?>">
                    <?php echo get_the_post_thumbnail($page->ID, 'original'); ?>
                </a>
            </div>
        </div> <!-- end boxy -->

1 个答案:

答案 0 :(得分:2)

我认为这就是你要做的事情:

$(".postmetadata:contains('Seattle')").each(function(){
    $(this).closest(".boxy").find(".storyNoImg").css("background-image","url(" + "images/seattle.png" + ")");
});

首先过滤所需的元素,然后使用each()

循环遍历它们

同样如前所述,jQuery对象没有contains()方法,添加类时不使用点