我正在从应用程序接收 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/