javascript - 如何用span替换字体标签?

标签 javascript jquery css

我正在尝试替换字体的所有实例 具有如下颜色属性的标签:

<font color="red">Some text</font>

这样:

<span style="color: red;">Some text</span>

我在 StackOverflow 上做了一些搜索,找到了这个链接,并根据它对我的代码进行了建模: Javascript JQuery replace tags

我在下面创建了一个小 jQuery 循环,它应该执行以下操作:

  1. 遍历字符串(div 的内容)
  2. 获取字体颜色属性
  3. 将标签替换为
  4. 使用适当的颜色设置 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/

相关文章:

javascript - Ajax 不传递参数

javascript - 使用 Internet Explorer 时,jQuery JSONP 请求经常失败

javascript - 尝试使用 AJAX 和 PHP

javascript - 发送服务器端 Google Analytics 数据而不发送服务器位置

jQuery 外部链接新窗口,尊重相对链接和与内部相同的域链接

javascript - 轮播需要在页面加载时从中间幻灯片开始

css - 位置 :fixed -- content disappearing on Zoom

javascript - 查询 : remove current div in image slider

javascript - 父组件和子组件在react-native中同时渲染

css - HTML5 & CSS 媒体属性媒体查询问题