我正在尝试替换字体的所有实例 具有如下颜色属性的标签:
<font color="red">Some text</font>
这样:
<span style="color: red;">Some text</span>
我在 StackOverflow 上做了一些搜索,找到了这个链接,并根据它对我的代码进行了建模: Javascript JQuery replace tags
我在下面创建了一个小 jQuery 循环,它应该执行以下操作:
- 遍历字符串(div 的内容)
- 获取字体颜色属性
- 将标签替换为
- 使用适当的颜色设置 CSS 样式属性。
现在,它不起作用。我刚刚收到一条错误消息,指出“replaceWith”不是函数。
$('font').each(function () {
var color;
this.$('font').replaceWith(function () {
color = this.attr("color");
return $('<span>').append($(this).contents());
});
this.$("span").attr("style", "color=" + color);
});
任何帮助将不胜感激!
最佳答案
没有必要每个都做,replaceWith 会在内部完成。
$("font").replaceWith( //find all font tags and call replace with to change the element
function(){
var tag = $(this);
return $("<span/>") //create new span
.html(tag.html()) //set html of the new span with what was in font tag
.css("color", tag.attr("color")); //set the css color with the attribute
}
);
JSFiddle:http://jsfiddle.net/qggadmmn/
关于javascript - 如何用span替换字体标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25507847/