Javascript 将几个div改为一个div
我有这个Javascript 将几个div改为一个div,javascript,regex,Javascript,Regex,我有这个 str = testString.replace(/<div style="(.*?)">(.*?)<\/div><div style="\1">/g, '<div style="$1">$2<br>'); str=testString.replace(/(.*)/g,$2); 它移除 <div style="text-align: right;">text1</div> <div style
str = testString.replace(/<div style="(.*?)">(.*?)<\/div><div style="\1">/g, '<div style="$1">$2<br>');
str=testString.replace(/(.*)/g,$2
);
它移除
<div style="text-align: right;">text1</div>
<div style="text-align: right;">text2</div>
text1
文本2
进入
text1
text2
太好了
如果我有多个
,该怎么办
我该怎么做
<div style="text-align: right;">text1</div>
<div style="text-align: right;">text2</div>
<div style="text-align: right;">text3</div>
<div style="text-align: right;">text4</div>
text1
文本2
文本3
文本4
进入
text1
text2
text3
text4
?您不能将正则表达式用于复杂的HTML操作!请 您可以使用jQuery操作DOM以获得相同的结果 这是来自fiddle的jQuery代码,假设所需的div位于id为
toParse
的包装div中
$('body').ready(function() {
var template = $('#toParse div').first().clone();
var result = "";
$('#toParse div').each(function(index, element) {
result += $(element).html();
result += "<br/>";
});
// you can add some extra code here to remove that
// extra final <br/>
$('#toParse').html($(template).html(result));
console.log(result);
});
$('body').ready(函数(){
变量模板=$('#toParse div').first().clone();
var结果=”;
$('#toParse div')。每个(函数(索引,元素){
结果+=$(元素).html();
结果+=“
”;
});
//您可以在这里添加一些额外的代码来删除它
//额外期末考试
$('#toParse').html($(模板).html(结果));
控制台日志(结果);
});
假设您已经从DOM中选择了第一个元素
var next = first.nextElementSibling;
while (next && next.nodeName.toUpperCase() === "DIV") {
first.appendChild(document.createElement('br'))
first.appendChild(next.firstChild)
next = next.nextElementSibling
}
刚刚意识到我们没有从DOM中删除空div。如果你想要的话,你可以这样做
var next;
while ((next = first.nextElementSibling) && next.nodeName.toUpperCase() === "DIV") {
first.appendChild(document.createElement('br'))
first.appendChild(next.firstChild)
next.parentNode.removeChild(next);
}
将html与正则表达式混为一谈只会导致痛苦、痛苦和心碎。你真的需要学习如何使用DOM操作来做这类事情。您建议如何使用jQuery进行此操作?
var next = first.nextElementSibling;
while (next && next.nodeName.toUpperCase() === "DIV") {
first.appendChild(document.createElement('br'))
first.appendChild(next.firstChild)
next = next.nextElementSibling
}
var next;
while ((next = first.nextElementSibling) && next.nodeName.toUpperCase() === "DIV") {
first.appendChild(document.createElement('br'))
first.appendChild(next.firstChild)
next.parentNode.removeChild(next);
}