使用js / jquery在包装div的出现中将html提取为两个字符串(在br标签上拆分)

时间:2013-09-26 22:50:57

标签: javascript jquery dom-manipulation

我在我的网站的某些页面中重复了以下简单的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)第一次休息之后和FINAL段落标记之前的所有内容。这可能包括各种各样的html,多段,子弹列表等。

有没有人有任何可靠而强大的代码可以做到这一点?

2 个答案:

答案 0 :(得分:1)

paragraph = []; 

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

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

//使用jQuery选择作为元素后代的段落元素,类为“aClass”

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

//获取在最后一行中选择的每个段落并将其拆分为“
”并将其推送到最后的数组中

});

//结束jQuery的每个函数

paragraphs = [];
$('.aClass p').each(function(){
    paragraphs.push( $(this).html().split('<br />') );
});

答案 1 :(得分: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/