按 BR 标记分隔行并添加跨度标记

  • 本文关键字:添加 BR 隔行 jquery
  • 更新时间 :
  • 英文 :


在父级.cycle-slide的幻灯片中,我正在努力从中获取以下段落文本示例

<p>First line<br>leads to second<br>and then a third</p>

对此使用JavaScript。我正在尝试按每个<br>拆分p,然后将文本包装在<span>

<p><span>First line</span><br><span>leads to second</span><br><span>and then a third</span></p>

我得到了这个,但它只显示在控制台.log()

jQuery('document').ready(function(){
    jQuery.each( jQuery( ".cycle-slide" ), function() {
        var data = jQuery(this).find('p').html().split('<br>');
        jQuery.each(data, function() {
            console.log(data);
            jQuery(data).wrap('<span>');
        });
    });
});

假设p元素只包含textNode s 和 br 元素,而不是拆分html内容并重置修改后的标记,您可以使用 .filter() 方法来选择文本 childNodes,并使用.wrap()方法来包装匹配的节点。

// `.contents()` method returns childNodes of the selected elements
$('p').contents().filter(function() {
    // `nodeType` of the `textNode` is 3
    return this.nodeType === 3;
}).wrap('<span/>');

http://jsfiddle.net/3Ky7S/

你应该更新元素的文本。

     jQuery('document').ready(function(){
         jQuery.each( jQuery( ".cycle-slide" ), function() {
             var data = jQuery(this).find('p').html().split('<br>');
             jQuery.each(data, function() {
                 console.log(data);
                 this.text(jQuery(data).wrap('<span>'));
             });
         });
     });

最新更新