【问题标题】:Strip code of all attributes and styling剥离所有属性和样式的代码
【发布时间】:2018-08-13 11:46:40
【问题描述】:

将产品上传到我的网站时,我通常会从制造商网站复制信息并粘贴到我的网站所见即所得编辑器中。这也会复制我不想要/不需要的所有属性和样式。

我创建了一个文件,该文件去除了该代码的所有属性和样式,以便我可以添加自己的。这是供完全不了解 HTML 的人使用的,所以我想知道是否有比我选择的方法更好的方法来做到这一点。

当前 div 附加了一些样式,因此当它被删除时,会有视觉反馈表明代码已被清理。

<button>Clean up code</button>

<div class="test" id="text" style="text-transform: uppercase;">

    <!-- PASTE YOUR CODE UNDER HERE -->

</div>

<script>


$( "button" ).click(function() {
    $("p").removeAttr("class").removeAttr("id").removeAttr("style");
    $("a").removeAttr("class").removeAttr("id").removeAttr("style");
    $("img").removeAttr("class").removeAttr("id").removeAttr("style");
    $("h1").removeAttr("class").removeAttr("id").removeAttr("style");
    $("h2").removeAttr("class").removeAttr("id").removeAttr("style");
    $("h2").removeAttr("class").removeAttr("id").removeAttr("style");
    $("h2").removeAttr("class").removeAttr("id").removeAttr("style");
    $("h3").removeAttr("class").removeAttr("id").removeAttr("style");
    $("h4").removeAttr("class").removeAttr("id").removeAttr("style");
    $("h5").removeAttr("class").removeAttr("id").removeAttr("style");
    $("h6").removeAttr("class").removeAttr("id").removeAttr("style");
    $("table").removeAttr("class").removeAttr("id").removeAttr("style");
    $("td").removeAttr("class").removeAttr("id").removeAttr("style");
    $("tr").removeAttr("class").removeAttr("id").removeAttr("style");
    $("ol").removeAttr("class").removeAttr("id").removeAttr("style");
    $("ul").removeAttr("class").removeAttr("id").removeAttr("style");
    $("li").removeAttr("class").removeAttr("id").removeAttr("style");
    $("tbody").removeAttr("class").removeAttr("id").removeAttr("style");    
    $("span").removeAttr("class").removeAttr("id").removeAttr("style");
    $( "div" ).contents().unwrap();
});
</script>

【问题讨论】:

    标签: jquery html code-cleanup


    【解决方案1】:

    您可以使用*,它基本上选择了所有元素。 removeAttrs 也可以是空格分隔的属性列表。

    $( "button" ).click(function() {
        $("*").removeAttr("class id style");
        $("div").contents().unwrap();
    });
    

    【讨论】:

    • 我知道有更简单的方法。我确实尝试分隔属性,但我使用逗号分隔并单独引用每个属性,这显然是错误的 - removeAttr("class", "id", "styles")。
    • 如果我还想 unwrap() 所有跨度标签,该怎么做?我试过 $("span").contents.unwrap() 没有运气,我能在网上找到的唯一解决方案似乎使用了比我预期的多得多的代码行。 contents().unwrap() 适用于表格元素,所以我认为这也适用。
    猜你喜欢
    • 2016-05-15
    • 2014-09-22
    • 1970-01-01
    • 2014-04-17
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    相关资源
    最近更新 更多