javascript - 使用 jquery find 更改节点

标签 javascript jquery dom find replacewith

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

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

我想做的是检查 div 的所有节点,并根据需要转换它们,但它似乎无法正常工作。当我按下按钮时,只有 div小学的 children 都变了。如果我再次按下按钮, child 的 child 就会改变,等等。 我不明白为什么它不会在第一次单击时更改所有节点。

这就是我得到的:

<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>

有人知道吗?

最佳答案

类似这样的吗?

 //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

关于javascript - 使用 jquery find 更改节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18839443/

相关文章:

javascript - 使用 jquery.each() 循环创建对象键

javascript - 为什么 Array.prototype.reduce() 不接受 Map 对象作为初始值?

javascript - datepicker() 代码的 jQuery 错误

javascript - 添加和删​​除类

javascript - 根据真/假条件构造对象

javascript - 检查是否选择了单选按钮

javascript - 如何过滤 JQuery 对象?

javascript - 在 Javascript 中拦截粘贴事件

php - DOM php按标签名称删除所有标签

javascript - 使用 jquery 或 javascript 在悬停图像时更改 href 属性