在幻灯片中,父级为 .cycle-slide
我正在努力获取以下段落文本示例
<p>First line<br>leads to second<br>and then a third</p>
使用 javascript 实现此目的。我正在尝试拆分 p
按每个<br>
然后将文本包裹在 <span>
中
<p><span>First line</span><br><span>leads to second</span><br><span>and then a third</span></p>
我得到了这个,但它只显示在 console.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
和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/>');
关于jquery - 通过 br 标签分割行并添加 span 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21831702/