【问题标题】:Jquery .html .slice, but retain formatting tagsJquery .html .slice,但保留格式化标签
【发布时间】:2019-05-15 21:00:46
【问题描述】:

我正在使用一个名为 dropcaps.js 的 jQuery 库来定位 <p> 标记的第一个字母,并将其包装在 span 中。这按预期工作,但是<p> 的其余部分已剥离所有标签,例如<a>、<strong>、<em> 等。有没有办法编辑以下内容以保留这些格式标签?

// Init dropcaps
// Dropcaps
$(document).ready(function() {
    // Isolate the first letter of paragraphs and place within <span>
    $('p.has-drop-cap').each(function() {
        var text = $.trim($(this).text());
        var firstLetter = text.substr(0,1);
        $(this).html('<span class="initial-letter">' + firstLetter + '</span>' + text.slice(1));
    }); 

    // Init dropcap.js and target <span>
    var dropcaps = document.querySelectorAll(".initial-letter");
    // Set dropcap number of rows to fit and baseline position
    window.Dropcap.layout(dropcaps, 5, 5);
});

【问题讨论】:

    标签: jquery html slice


    【解决方案1】:

    使用html()而不是text()来获取内容字符串为html

    您还可以使用html(function) 代替each 进行一些简化

    $('p.has-drop-cap').html(function(_, currHtml) {
      currHtml = $.trim(currHtml);
      var firstLetter = currHtml.substr(0, 1);
      return '<span class="initial-letter">' + firstLetter + '</span>' + currHtml.slice(1));
    });
    

    请注意,这假设所有段落都以原始文本开头,并且没有像 &lt;b&gt;、&lt;strong&gt;、&lt;img&gt; 等这样的直系子代

    【讨论】:

    • 感谢@charlietfl 的回复!不幸的是,这似乎不起作用,它仍然会删除所有内容?
    • 在 jsfiddle 或其他沙盒站点中创建一些示例段落
    猜你喜欢
    • 1970-01-01
    • 2018-04-14
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多