【问题标题】:jQuery append span if parent class exists如果父类存在,则jQuery追加跨度
【发布时间】:2014-06-03 01:36:28
【问题描述】:

这是我的目标:

如果任何父 <li> 具有类 outofstock,我想在 .inner_product_header 内附加一个 <span>(在 onsale 范围之后)。

我的代码:

HTML:

<ul class="products">
<li class="product outofstock"> <a href="#">
    Test text description
        <div class="inner_product_header">
            <span class="onsale">On Sale</span>
        </div>
    </a>

</li>
<li class="product"> <a href="#">
    Test text description
    <div class="inner_product_header">
            <span class="onsale">On Sale</span>
        </div>
    </a>

</li>
</ul>

JS:

$(function() {

    if ( $( 'ul.products li.product' ).hasClass( 'outofstock' ) ) {

    $(this).children('.inner_product_header').append('<span class="itscomingsoon">Coming Soon</span>');

}

});

这是我的 jsFiddle 样式以查看块:http://jsfiddle.net/8szFV/4/

我不知道哪里出错了。有什么想法吗?

【问题讨论】:

    标签: jquery class append html


    【解决方案1】:

    在您的代码中,您使用的是$(this),但您不在绑定this 的事件处理程序或.each() 循环中。

    但您可以在一条线中完成所有操作。

    jQuery(function($) {
        $("ul.products li.product.outofstock .inner_product_header").append('<span class="itscomingsoon">Coming Soon</span>');
    });
    

    DEMO

    【讨论】:

    • 谢谢@Barmar!绝对是更简洁的解决方案。但是,在我的网站上,它仍然没有在 onsale 跨度之后附加跨度。
    • 很奇怪,因为它无法在实时站点上运行:lifelongu.com/life-balance。它正在加载.js 很好,但没有&lt;span&gt;Coming Soon!&lt;/span&gt; 出现在任何.inner_product_headers 中。
    • 找到了,comingsoon.js。您需要将它包装在$(function() ...) 中,就像您的问题一样,所以它会在 DOM 加载后运行。
    • @Barmar:这段代码仍然无法使用,因为他使用的是.noConflict()
    • 修复了我的答案来解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-11
    • 2020-07-03
    • 2021-02-12
    • 2013-10-03
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多