我有一个字符串,我希望在每个</div>
之后断开并插入数组。以下是字符串。
"<DIV title='Run of Network' id='525000000'>Run of Network</DIV>
<div title='3dServer11' id='525001499'>3dServer11</div>"
我想过使用split()
函数,但由于这不是逗号分隔的字符串,我无法准确理解应该如何打破字符串并生成数组。在数组中我想要单个单个div条目,如:
a[0] = <DIV title='Run of Network' id='525000000'>Run of Network</DIV>
a[1] = <div title='3dServer11' id='525001499'>3dServer11</div>"
任何人都可以帮忙吗?提前谢谢。
答案 0 :(得分:4)
我不建议您使用split
方法拆分HTML字符串或parse it with regular expressions。使用DOM方法操作元素总是更好:
var str = "<DIV title='Run of Network' id='525000000'>Run of Network</DIV>\
<div title='3dServer11' id='525001499'>3dServer11</div>",
div = document.createElement("div"),
arr = [];
div.innerHTML = str;
arr = Array.prototype.slice.call(div.getElementsByTagName("div"));
arr = arr.map(function(e) { return e.outerHTML; }); // to create strings
// out of DOM elements
console.log(arr);
答案 1 :(得分:3)
尝试
<div id="container"></div>
<script>
$(document).ready(function () {
var str = "<div title='Run of Network' id='525000000'>Run of Network</div><div title='3dServer11' id='525001499'>3dServer11</div>";
$("#container").html(str);
for (i = 0; i < $("#container").children().length; i++) {
alert($("#container").children()[i].innerHTML);
}
});
答案 2 :(得分:2)
<强>更新强>:
如果您有一个想要执行相同操作的DOM元素,请写一个小的jQuery插件:
(function($) {
$.fn.splitDOMStringsByTag = function( selector ) {
var resultsArray = [];
this.find( '> ' + selector).each(function() {
resultsArray.push( $(this)[0].outerHTML.replace( /[\s\n\r]+/g, ' ' ) );
});
return resultsArray;
};
})( jQuery );
这是如何运作的:
假设您有以下DOM
<ul id="abc">
<li>One </li>
<li>Two </li>
<li>Three </li>
<li>Three
<ul>
<li>Three point five</li>
</ul>
</li>
<li>Four </li>
</ul>
然后您将执行以下操作:
var myArray = $('#abc').splitDOMStringsByTag('li');
获取以下输出
myArray; // console
["<li>One </li>", "<li>Two </li>", "<li>Three </li>", "<li>Three <ul> <li>Three point five</li> </ul> </li>", "<li>Four </li>"]
myArray[3] // console
"<li>Three <ul> <li>Three point five</li> </ul> </li>"
使用普通JS的旧答案
var ipt = "<DIV title='Run of Network' id='525000000'>Run of Network</DIV><div title='3dServer11' id='525001499'>3dServer11</div>",
dummyDiv = document.createElement("div"),
divList = [],
a = [];
dummyDiv.innerHTML = ipt;
divList = Array.prototype.slice.call(dummyDiv.getElementsByTagName("div"));
for (var i = 0; i < divList.length; i++) {
a.push(divList[i]);
}
这会为您提供所需的a
a[0] = <DIV title='Run of Network' id='525000000'>Run of Network</DIV>
a[1] = <div title='3dServer11' id='525001499'>3dServer11</div>
要获取字符串,只需使用a[0].outerHTML
a[0].outerHTML;
// Console Output
"<div title="Run of Network" id="525000000">Run of Network</div>"