Kyl*_*yle 7 javascript jquery dom-manipulation replacewith
文本
变成
<p href="page.html" class="class1 class2" id="thisid">Text</p>
Run Code Online (Sandbox Code Playgroud)
我熟悉jQuery,replaceWith但据我所知,这并没有保留属性/内容.
注意:为什么p会有href?因为我需要改p回a另一个事件.
小智 18
这是一个更通用的方法:
// New type of the tag
var replacementTag = 'p';
// Replace all a tags with the type of replacementTag
$('a').each(function() {
var outer = this.outerHTML;
// Replace opening tag
var regex = new RegExp('<' + this.tagName, 'i');
var newTag = outer.replace(regex, '<' + replacementTag);
// Replace closing tag
regex = new RegExp('</' + this.tagName, 'i');
newTag = newTag.replace(regex, '</' + replacementTag);
$(this).replaceWith(newTag);
});
Run Code Online (Sandbox Code Playgroud)
你可以在这里试试代码:http://jsfiddle.net/tTAJM/
这是我用来替换jquery中的html标签的方法:
// Iterate over each element and replace the tag while maintaining attributes
$('a').each(function() {
// Create a new element and assign it attributes from the current element
var NewElement = $("<p />");
$.each(this.attributes, function(i, attrib){
$(NewElement).attr(attrib.name, attrib.value);
});
// Replace the current element with the new one and carry over the contents
$(this).replaceWith(function () {
return $(NewElement).append($(this).contents());
});
});
Run Code Online (Sandbox Code Playgroud)
我通常也会将其限制为特定的类,$('a.class1').each(function()例如上面的例子.
最好为未来的可重用性创建jQuery插件:
(function (a) {
a.fn.replaceTagName = function (f) {
var g = [],
h = this.length;
while (h--) {
var k = document.createElement(f),
b = this[h],
d = b.attributes;
for (var c = d.length - 1; c >= 0; c--) {
var j = d[c];
k.setAttribute(j.name, j.value)
}
k.innerHTML = b.innerHTML;
a(b).after(k).remove();
g[h - 1] = k
}
return a(g)
}
})(window.jQuery);
Run Code Online (Sandbox Code Playgroud)
用法:
// Replace given object tag's name
$('a').replaceTagName("p");
Run Code Online (Sandbox Code Playgroud)
示例:JSFiddle
Moi*_*man -2
尝试这个:
var $a = $('a#thisid');
var ahref = $a.attr('href');
var aclass = $a.attr('class');
var aid = $a.attr('id');
var atext = $a.text();
$a.replaceWith('<p href="'+ ahref +'" class="'+ aclass +'" id="'+ aid+'">'+ atext +'</p>');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10339 次 |
| 最近记录: |