【问题标题】:Replacing the Element with specific attribute and its value用特定属性及其值替换元素
【发布时间】:2010-05-24 17:57:05
【问题描述】:
<p>
lorem ipsum lorem ipsums <font style="background-color:yellow">ipsum</font> ipsume lorem
</p>
如何将<font> 标记替换为<abbr>,这样输出会是这样的。
<p>
lorem ipsum lorem ipsums <abbr style="background-color:yellow">ipsum</abbr> ipsume lorem
</p>
【问题讨论】:
标签:
javascript
jquery
html
【解决方案1】:
在任何 p 中查找所有字体标签,并将其替换为带有样式属性和复制文本的 abbr。
$("p font").each(function() {
var font = $(this);
var abbr = $("<abbr>", {
style: font.attr("style"),
text: font.text()
});
font.replaceWith(abbr);
});
【解决方案2】:
这会将所有<font 和</font 替换为<abbr 和</abbr。
var p = document.getElementsByTagName("p")[0]; // assume this is the first P in the document
var p.innerHTML = p.innerHTML.replace(/(<|<\/)font/g, "$1abbr")
【解决方案3】:
也许您可以使用getAttributes plugin 来复制您的属性:
var attributes =$.getAttributes($(YOURTAG));
$(YOURTAG).replaceWith($('<abbr>' + YOURTAG.innerHTML + '</abbr>');
$(YOURTAG).attr(attributes);
注意:对不起,我没有测试这个...
【解决方案4】:
这应该可以解决问题。
$('p').each(
function(){
$(this).html($(this).html().replace(/(<|<\/)font/g, "$1abbr"));
}
);
【解决方案5】:
我有这个:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<style type="text/css"><!--
--></style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript"><!--
$(function(){
$("font").replaceWith(function(){
var font = $(this);
return $("<abbr></abbr>")
.attr("style", font.attr("style") )
.append( font.contents() );
});
});
//--></script>
</head>
<body>
<p>
lorem ipsum lorem ipsums <font style="background-color:yellow">ipsum</font> ipsume lorem
</p>
</body>
</html>
可能有更直接的方法,但这似乎可行。