【发布时间】:2011-06-26 08:03:28
【问题描述】:
我有这样的事情:
<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);
【讨论】:
您应该使用要更改的HTMLElement 的outerHtml 属性。
通过这种方式,将span 更改为anchor 变得非常容易:我们只需将^<span 替换为<a 并将</span>$ 替换为</a>。
使用正则表达式仅更改开始和结束标记的第一次和最后一次出现,我们保持原来的属性。
代码在这里:
var newElement = $('a-selector').get(0).outerHTML.replace(/^<span/, "<a").replace(/<\/span>$/, "</a>");
$('a-selector').replaceWith(newElement);
此示例使用 jQuery。请参阅此fiddle 以查看它的工作原理。
【讨论】:
您实际上想在这里实现什么目标?如果只是样式,那么使用 CSS 会更好。如果您希望某些内容成为可点击的链接(或成为不可点击的链接),那么您只需删除 href 属性即可。
【讨论】:
我不打算编写代码,但要引导您朝着正确的方向前进,请查找如何在 jquery 中构建标签(类似于 http://api.jquery.com/append/)
然后用Iterating over element attributes with jQuery之类的东西循环遍历每个标签,并将每个属性添加到附加的标签中。
编辑:很好,这是一个例子:http://jsfiddle.net/mazzzzz/xUUn3/
【讨论】:
$('#thetagidORsomething').append('<span>tag</span>').attr('id','tmp'); 之类的东西创建新标签然后在循环内部将每个属性分配给id 为tmp 的项目。我在帖子中添加了一个示例。
这是我在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());
});
});
我在第一行使用的each 函数在这种情况下有点不必要,因为我们只通过 id 选择单个项目。我仍然更喜欢在这里使用each,因为这将允许相同的代码循环遍历具有特定类的所有项目。
【讨论】:
您可以将此代码与 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>');
【讨论】: