【问题标题】:Changing nodes with jquery find使用 jquery find 更改节点
【发布时间】:2013-09-21 06:39:27
【问题描述】:

我正在从应用程序接收 HTML 数据,但我需要更改一些节点以使其与新应用程序兼容,例如将 <b> 更改为 <strong>

我写了这个例子http://jsfiddle.net/daYL4/9/

我想要做的是检查div 的所有节点,并在需要时对其进行转换,但它似乎无法正常工作。当我按下按钮时,只有div 主要孩子被改变。如果我再次按下按钮,孩子的孩子会改变,等等。 我不明白为什么它不会在第一次点击时更改所有节点。

这是我得到的:

<font>span
    <b>bbb<i>iii</i>bbb<i>iii</i>bbb<i>i<font>font</font>ii</i></b>
</font>

这就是我按下按钮时想要的:

<span>span
        <strong>bbb<em>iii</em>bbb<em>iii</em>bbb<em>i<span>font</span>ii</em></strong>
    </span>

有人知道吗?

【问题讨论】:

    标签: javascript jquery dom find replacewith


    【解决方案1】:

    这样的?

     //create a jquery function for ease of operation.
    $.fn.transform = function(replacer){
        replacer = replacer || {};
        this.find('*').each(function(){
            var newNode = replacer[this.nodeName];
            if(this.nodeType == 1 && newNode){//check for element node and if it is one in the replacement object
                $(this).contents().unwrap().wrapAll(newNode); // take the contents out of the element unwrap it and then wrap all of the contents by creating a new object based on the replacement object value.
            }
        });
        return this; //return for chaining
    }
    
    $(document).ready(function() {
        $("button").click(function() {
    
            //create an object with key value pair of replacement required
            var repl = {
                'B' :'<strong/>',
                'I' : '<em/>',
                'FONT': '<span/>'
            }
            $("div").transform(repl);
        });    
    });
    

    Fiddle

    【讨论】:

    • 而且该方法也是可链接的:)。
    • 这太完美了!!谢谢 ! :))
    猜你喜欢
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 2016-02-19
    • 2013-12-09
    相关资源
    最近更新 更多