4

我在我的网站的某些页面中重复了以下简单的 html 块:

<div class="aClass">
<p>first part<br />the remainder of the content</p>
<p>another paragraph><img src="anImage.jpg"/></p>
</div>

我想要做的是在我的代码中找到带有 aClass 的 div 时捕获并创建两个字符串。我希望每次出现的两个字符串都包含...

1)从第一个段落开始标记之后到第一个中断的所有内容 2)第一个中断之后和最后一个段落标记之前的所有内容。这可能包括各种 html、多个段落、项目符号列表等。

有没有人有任何可靠且健壮的代码可以做到这一点?

4

2 回答 2

3
paragraph = []; 

初始化数组以存储段落内容

$('.aClass p').each(function(){ 

使用 jQuery 选择属于“aClass”类的元素的后代的段落元素

paragraphs.push( $(this).html().split('<br />') );

获取在最后一行中选择的每个段落并将其拆分到<br />html 标记上,并将其推入段落数组末尾的新位置

});

结束 jQuery.each 函数

paragraphs = [];
$('.aClass p').each(function(){
    paragraphs.push( $(this).html().split('<br />') );
});
于 2013-09-26T23:06:40.543 回答
0
$(".aClass p").each(function(){
  var strings = $(this).html().split(/<br\s*\/?>/);
  // if there is more than two parts this will cover it
  strings = [strings.shift(), strings.pop()];
  // could also do this if you wanted a trimmed array result
  // strings = strings.splice(1, strings.length-2||0)
  // remember that split on a valid string (including empty) will return at least one entry 
  console.dir(strings);
})

http://jsfiddle.net/24b2b/

于 2013-09-26T23:09:35.447 回答