更改标记但保留属性和内容 – jQuery / Javascript
文本
变成
Text
我熟悉jQuery的replaceWith
但据我所知,这并没有保留属性/内容。
注意:为什么p会有href
? 因为我需要将p
改回另一个事件。
试试这个:
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(''+ atext +'
');
这是一个更通用的方法:
// 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); });
你可以在这里试试代码: 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 = $(""); $.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()); }); });
我通常也会将它限制为一个特定的类,例如$('a.class1').each(function()
上面例子中的$('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);
用法:
// Replace given object tag's name $('a').replaceTagName("p");
示例: JSFiddle
hacky做的伎俩
var p = $('a').wrapAll(''); var a = $('div').map(function(){ return this.innerHTML; }).get().join(' '); $('div.replace').html(a.replace(//g,'p>'));
演示
我把它变成了一个简单的javascript函数:
function ReplaceTags(Original, Replace){ var oarr = document.getElementsByTagName(Original); for(i=0; oarr.length < i; i++){ var html = oarr[i].outerHTML; oarr[i].outerHTML = (html.replace(Original, Replace)); } }
如果您只想替换特定标记,只需删除for循环:
function ReplaceTag(Original, Replace, customi){ // If customi = 0 the first appearance will get replaced var i = customi; if(i == undefined) i=0; var oarr = document.getElementsByTagName(Original); var html = oarr[i].outerHTML; oarr[i].outerHTML = (html.replace(Original, Replace)); }