在每个图像标记之前拆分HTML

时间:2014-07-25 06:38:57

标签: javascript jquery html split

<div id="d">
  <p>one</p>
  <p>two</p>
  <img class="select image" src="something">
  <p>SPLIT HERE<p>
  <p>More Split</p>
  <img class="select image 2" src="something">
  <img class="select image 3" src="something">
  <p>more split here<p>
</div>

<script>
  // Pseudo Javascript:
  $('#d').find('img').each(function(){
    var split = split.images();
    alert(split);
  });
  alert(lastSplit);
</script>

在图像之后

split => <p>one</p><p>two</P>

第二张图片后:

split => <p>SPLIT HERE<p>
         <p>More Split </p>

第三张图片后

split => ""

如果最后一张图片后面有任何文字,则应存储在最后一张图片

last split (if any) => <p>more split here<p>

我想让它变得通用,因为我不知道HTML页面中会有多少个图像标记。有人可以给我一个现场演示吗? 输出div应该是这样的

<div id=\"d\"<p>one</p><p>two</p>     select image     <p>SPLIT HERE<p><p>More Split </p>     select image 2     select image 3     <p>more split here<p></div>

2 个答案:

答案 0 :(得分:0)

如果我理解你的问题,this should do what you're after。关键是要遍历兄弟节点,每次找到img标签时都要分开:

var splitAtImages = function($parent) {
    var splits = [];
    var currentSplit = [];

    $parent.children().each(function() {
        var $this = $(this);
        if ($this.is("img")) {
            splits.push(currentSplit);
            currentSplit = [];

        } else {
            // Use this to push the whole node
            // currentSplit.push($this);

            // Or, use this to push just the HTML of the node
            currentSplit.push($this[0].outerHTML);
        }
    })

    if (currentSplit.length)
        splits.push(currentSplit);

    return splits;
}

这可能不是你需要的,但至少应该让你开始。

答案 1 :(得分:0)

var x = [],
    y = "",
    count = 0;


$("#d").children().each(function () {
    x.push($(this));
    if (this.tagName.toLowerCase() == "img") {
        count++;
        y += "Before Image " + count + ": ";

        for (var i = 0; i < x.length; i++) {
            y += " " + x[i].text().trim() + " ";
        }

        y += "\n";

        x = [];
    }
});

if (x.length > 0) {
    y += "Remaining text: ";
    for (var i = 0; i < x.length; i++) {
        y += "\n - " + x[i].html();
    }

}
console.log(y);

JS FIddle