Jquery 更改标记名,但保留所有属性
我有这样的想法:Jquery 更改标记名,但保留所有属性,jquery,Jquery,我有这样的想法: <span id="anId" someOtherAttributes....>test</span> 测试 我想换成: <a id="anId" theSameOtherAttributes...>test</a> 测试 我有两个问题: 如何更改标签名 或 如何复制所有属性 我不打算编写代码,但为了让您了解正确的方向,请查找如何在jquery中构建标记(类似于) 然后使用类似的
<span id="anId" someOtherAttributes....>test</span>
测试
我想换成:
<a id="anId" theSameOtherAttributes...>test</a>
测试
我有两个问题:
我不打算编写代码,但为了让您了解正确的方向,请查找如何在jquery中构建标记(类似于) 然后使用类似的内容循环遍历每个标记,并将每个属性添加到附加的标记中
编辑:好的,这里有一个例子:这里有一个不优雅但有效的解决方案:
// create a new <a> element
new_element = $("<a/>");
// iterate over every attribute of the #some_id span element
$.each($("#some_id").get(0).attributes, function(i, attrib) {
// set each attribute to the specific value
$(new_element).attr(attrib.name, attrib.value);
});
// carry over the html content
new_element.html($("#some_id").html());
// finally, swap the elements
$("#some_id").replaceWith(new_element);
//创建新元素
新的_元素=$(“”);
//迭代#some_id span元素的每个属性
$.each($(“#some_id”).get(0).属性,函数(i,attrib){
//将每个属性设置为特定值
$(新元素).attr(attrib.name,attrib.value);
});
//携带html内容
new_element.html($(“#some_id”).html();
//最后,交换元素
$(“#某些_id”)。替换为(新的_元素);
您在这里真正想要实现什么?如果只是样式,那么使用CSS会更好。如果您希望某个内容成为可单击的链接(或不可单击的链接),则只需删除href
属性。您应该使用要更改的HTMLElement
的outerHtml
属性
通过这种方式,将
span
更改为a
nchor变得非常容易:我们只需要替换^以下是我用来替换jquery中html标记的方法:
// Iterate over each element and replace the tag while maintaining attributes
$('span#anId').each(function() {
// Create a new element and assign it attributes from the current element
var NewElement = $("<a />");
$.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());
});
});
//迭代每个元素并在维护属性的同时替换标记
$('span#anId')。每个(函数(){
//创建新元素并从当前元素为其指定属性
var NewElement=$(“”);
$.each(this.attributes,function(i,attrib){
$(新元素).attr(attrib.name,attrib.value);
});
//将当前元素替换为新元素并保留内容
$(this).replaceWith(函数(){
返回$(NewElement).append($(this.contents());
});
});
在这种情况下,我在第一行使用的每个
函数有些不必要,因为我们只根据id选择一个项目。我仍然更喜欢在这里使用每个
,因为这将允许相同的代码在具有特定类的所有项目中循环。您可以在jQuery中使用此代码:
function replaceElementTag(targetSelector, newTagString) {
$(targetSelector).each(function(){
var newElem = $(newTagString, {html: $(this).html()});
$.each(this.attributes, function() {
newElem.attr(this.name, this.value);
});
$(this).replaceWith(newElem);
});
}
用法和示例:
replaceElementTag('img', '<amp-img></amp-img>');
replaceElementTag('img','');
这似乎没有带属性,但当我使用el.attributes时,我得到了“未定义”。但我尝试了el.attr(“类”),我有一些东西。那么为什么el.attributes返回未定义?el在哪里。来自哪里?在循环中有两个变量专门用于属性名称和值,只需使用类似于$('#thetagiorsomething')的内容创建新标记即可。append('tag')。attr('id','tmp')
然后在循环内部将每个属性分配给id为tmp
的项。我在帖子中添加了一个例子。
replaceElementTag('img', '<amp-img></amp-img>');