jquery - 整合堆栈的DOM元素 [英] jquery - consolidate stacked DOM elements

查看:90
本文介绍了jquery - 整合堆栈的DOM元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTML格式通过contenteditable div格式。我想让它更简洁,现代的HTML。我可以轻松地替换任何b,strong,em,font等标签,并用span替换它们,但结果产生了堆叠元素。



例如,我可能有:

 < span style =font-weight:bold> 
< span style =text-decoration:underline>一些文本< / span>
< / span>

我想看看:

 < span style =font-weight:bold; text-decoration:underline>一些文本< / span> 

困难的部分是需要处理:

 < span style =font-weight:bold> 
< span style =text-decoration:underline>一些文本< / span>没有下划线
< / span>

我已经做了很多的搜索和思考,但没有发现任何合理的

解决方案

嗯,这是一个开始。显然,您的选择器将比仅仅 span 更具体。

  $( span)。each(function(){
var $ this = $(this);
var $ contents = $(this).contents();

if ($ contents.length === 1& $ contents.is(span)){
//只有一个孩子(包括文本节点),它是一个跨度,合并
copyStylesFromParentToChild (); //需要实现这个

$ this.replaceWith($ this.children()); //将父代替为子
}
});

这里唯一棘手的部分是 copyStylesFromParentToChild 。我不知道将所有样式从一个元素复制到另一个元素的简单直接方法。您可以尝试 JavaScript&复制样式


I have HTML that was formatted via a contenteditable div. I am wanting to make it more concise, modern HTML. I can easily replace any b, strong, em, font, etc tags and replace them with spans, but the result produced "stacked" elements.

For instance, I might have:

<span style="font-weight:bold">
    <span style="text-decoration:underline">some text</span>
</span>

And I want to see:

<span style="font-weight:bold; text-decoration:underline">some text</span>

The hard part is it would need to handle:

<span style="font-weight:bold">
    <span style="text-decoration:underline">some text</span> not underlined
</span>

I've done quite a bit of searching and thinking about this, but haven't found anything reasonable.

解决方案

Well, here's a start. Obviously your selector would be more specific than just span.

$("span").each(function(){
    var $this = $(this);
    var $contents = $(this).contents();

    if($contents.length === 1 && $contents.is("span")){
        // only one child (including text nodes) and it is a span, combine
        copyStylesFromParentToChild();  // need to implement this

        $this.replaceWith($this.children());  // replace the parent with the child
    }
});

The only tricky part here is copyStylesFromParentToChild. I don't know any easy straightforward way to copy all styles from one element to another. You can try JavaScript & copy style

这篇关于jquery - 整合堆栈的DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆