使用"match"将内容插入到 div 中,而不会覆盖所有内部 HTML



有人让我想到了使用"match"来针对具有"ly_productdetails productdetails en en_GB"主体类的页面,以便在页面(容器)上填充特定的div。

这解决了我在div为空但如果存在HTML则替换所有内容的场景中的问题。

我该如何修改我的JS以不替换内容,而是先添加新的代码段,然后再添加现有内容?

提前谢谢。

$(function() {    // document ready
    var body = $(document.body);    // body element
    // If match and length then modify html
    if (body.attr('class').match(/ly_productdetails ProductDetails en en_GB/).length > 0) {
        $('#container').html("<div><h1>Products</h1></div>");
    }
});

我该如何修改我的JS以不替换内容,而是先添加新的代码段,然后再添加现有内容?

您应该使用.prepend()而不是.html()来将内容附加为第一个元素:

if (body.attr('class').match(/ly_productdetails ProductDetails en en_GB/).length > 0) {
    $('#container').prepend("<div><h1>Products</h1></div>");
}

我永远不会使用这种人为的订单特定的方式。如果你只使用几个hasClass调用的组合,阅读起来会容易得多:

$(function() {    // document ready
    var $body = $(document.body);    // body element
    // If match
    if ($body.hasClass('ly_productdetails') && $body.hasClass("ProductDetails") && $body.hasClass("en") && $body.hasClass("en_GB") {
        $('#container').prepend("<div><h1>Products</h1></div>");
    }
});

由于Regex本质上比大多数字符串操作慢,因此速度差异可以忽略不计(并且在页面加载时只发生一次)。

当然(最后阅读您的实际问题),您还需要prepend内容,而不是替换它:)

最新更新