jQuery .html .slice,但保留格式标记

时间:2018-12-14 15:08:56

标签: jquery html slice

我正在使用一个名为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);
});

1 个答案:

答案 0 :(得分:0)

使用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));
});

请注意,这假定所有段落均以原始文本开头,并且没有像<b><strong><img>等这样的直接子代