![](/img/trans.png)
[英]Change video tag attributes depending on device width (JQuery/Javascript)
[英]Change the tag but keep the attributes and content — jQuery/Javascript
<a href="page.html" class="class1 class2" id="thisid">Text</a>
改為
<p href="page.html" class="class1 class2" id="thisid">Text</p>
我熟悉 jQuery 的replaceWith
但據我所知,它並沒有保留屬性/內容。
注意:為什么 p 會有一個href
? 因為我需要在另一個事件中將p
改回a
。
這是一個更通用的方法:
// 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 = $("<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());
});
});
我通常還會將其限制為特定的類,例如上面示例中的$('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('<div class="replace"></div>');
var a = $('div').map(function(){
return this.innerHTML;
}).get().join(' ');
$('div.replace').html(a.replace(/<a/g,'<p').replace(/a>/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));
}
試試這個:
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>');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.