如何解决Javascript:在循环中将文字 HTML 结果加在一起
JS 新手。我能找到的所有标题与我的标题相似的问题都太复杂了,我无法理解。
简单地说,我试图遍历一个数组并在最后返回一个结果,该结果基本上将数组的所有值添加/连接在一起。
但是,我似乎无法让它工作,因为数组中的项目是 HTML 代码块,而不是简单的字符串或数字。这是一个简化版。
HTML:
<article class="wrapper"><p>Some text 1.</p></article>
<article>No class.</article>
<article class="wrapper"><p>Some text 2.</p></article>
<article>No class.</article>
<article class="wrapper"><p>Some text 3.</p></article>
我试图找出一种方法来结束这段代码的模板文字:
<article class="wrapper"><p>Some text 1.</p></article>
<article class="wrapper"><p>Some text 2.</p></article>
<article class="wrapper"><p>Some text 3.</p></article>
这样我就可以将整个内容作为另一个页面上另一个元素的 innerHTML 注入。
从这个 JS 开始:
articleArray = document.querySelectorAll('.wrapper').outerHTML;
console.log(articleArray)
// This will return an array with the full HTML of the 3 "wrapper" articles as each item
然后尝试创建一个循环,该循环将在第一个循环中获取第 1 项的完整 HTML,并将其设置为类似于累加器值的内容。然后在第二个循环中,它将获取第 2 项的完整 HTML 并将其直接连接到第 1 项,这将是新的累加器值。等等。
对于我在现实生活中应用的内容,我有超过 3 个项目,否则我可以做一些类似 articleArray[0] + articleArray[1] + articleArray[2] 的事情。
我尝试了一百万次,但最接近的尝试如下:
- 记录
var articleArray = document.querySelectorAll('.wrapper').outerHTML;
for (i = 0; i < searchWrappers.length; i++) {
searchWrapper = articleArray[i];
console.log(searchWrapper);
}
// Console log brought back 3 objects,but I need to combine them
- 串联
var articleArray = document.querySelectorAll('.wrapper').outerHTML;
var searchStr = ''
for (i = 0; i < articleArray.length; i++) {
itemHTML = articleArray[i];
fullString = searchStr += itemHTML;
console.log(fullString);
}
// This did concatenate the 3 items,but only as:
// [object HTMLElement][object HTMLElement][object HTMLElement]
// and not the actual HTML
- 连接和记录
const articleArray = document.querySelectorAll('.wrapper').outerHTML;
const sum = articleArray.reduce((accumulator,value) =>
$(accumulator).concat($(value)));
console.log(sum);
// This brought back a normal array of the 3 items again
感谢任何帮助!
编辑:感谢您的所有回复!我现在将通过它们并在我的真实代码上测试您的解决方案,看看什么最有效。
解决方法
这应该对您有所帮助:
function contains(selector,text) {
var elements = document.querySelectorAll(selector);
return [].filter.call(elements,function (element) {
return RegExp(text).test(element.textContent);
});
}
var articleArray = contains(".wrapper",'menu');
// var articleArray = contains(".wrapper",/menu/i); // for case-insensitive
let templateLiteral = ``;
articleArray.forEach(function (article) {
templateLiteral += article.outerHTML + '\n';
})
console.log(templateLiteral);
article {
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<article class="wrapper"><p>Some text 1. menu</p></article>
<article>No class.</article>
<article class="wrapper"><p>Some text 2. menu</p></article>
<article>No class.</article>
<article class="wrapper"><p>Some text 3.</p></article>
</body>
</html>
基本思想是遍历每个 HTML 元素并将元素的 outerHTML
添加到模板文字中。
编辑:多亏了 this answer,它帮助我实现了在 jQuery 中找到 :contains
的 vanilla js 替代品的预期效果。
您可以将元素映射到它们的外部 HTML,然后加入结果。
const htmlString = [...document.querySelectorAll('.wrapper')]
.map(({ outerHTML }) => outerHTML.trim())
.join('\n');
console.log(htmlString);
.as-console-wrapper { top: 0; max-height: 100% !important; }
.wrapper { display: none; }
<article class="wrapper">
<p>Some text 1.</p>
</article>
<article>No class.</article>
<article class="wrapper">
<p>Some text 2.</p>
</article>
<article>No class.</article>
<article class="wrapper">
<p>Some text 3.</p>
</article>
您可以通过以下方式创建模板,通过连接每篇文章 outerHTML
:
var articleArray = document.querySelectorAll('.wrapper');
var template = '';
articleArray.forEach(article => template += article.outerHTML);
console.log(template)
如果您需要检查每篇文章中是否有多余的词(例如'menu'
),您可以添加以下条件:
articleArray.forEach(article => {
if (article.innerText.includes('menu')) {
template += article.outerHTML.trim()
}
});
,
您也可以只获取包装器并将它们推送到新元素中以制作模板:
let result = document.createElement("div")
document.querySelectorAll('.wrapper').forEach(e =>
result.insertAdjacentElement("beforeend",e))
console.log(result.innerHTML)
<article class="wrapper">
<p>Some text 1.</p>
</article>
<article>No class.</article>
<article class="wrapper">
<p>Some text 2.</p>
</article>
<article>No class.</article>
<article class="wrapper">
<p>Some text 3.</p>
</article>
然后就可以用result.innerHTML
全部转移了。
另见:Element.insertAdjacentElement()
编辑: 您实际上需要使用克隆,以便不会从 DOM 中删除包装器:
let result = document.createElement("div")
document.querySelectorAll('.wrapper').forEach(e => {
let cln = e.cloneNode(true)
result.insertAdjacentElement("beforeend",cln)
})
console.log(result.innerHTML)
<article class="wrapper">
<p>Some text 1.</p>
</article>
<article>No class.</article>
<article class="wrapper">
<p>Some text 2.</p>
</article>
<article>No class.</article>
<article class="wrapper">
<p>Some text 3.</p>
</article>
DOMParser 是正确的工具,如果您确实拥有:
“数组中的项目是 HTML 代码块”
// I have an array of elements as HTML strings:
const elArray = [
`<article class="wrapper"><p>Some text 1.</p></article>`,`<article>No class.</article>`,`<article class="wrapper"><p>Some text 2.</p></article>`,`<article class="wrapper"><p>Some text 3.</p></article>`,];
// DOMParser is the right tool for the job!
const DOC = new DOMParser().parseFromString(elArray.join(""),"text/html");
// Use selectors as normal!
const ELs = DOC.querySelectorAll(".wrapper");
// DEMO TIME: retrieve elements and finally
// place them somewhere in the app
document.querySelector("#test").append(...ELs);
<div id="test"></div>
如果您实际上有一个 NodeList 元素:
- document.querySelectorAll("article.wrapper");将您的 3 个元素作为非实时 NodeList
- Array.prototype.reduce() 减少三个元素 outerHTML 到单个字符串!
// I am trying to figure out a way to end up
// with a template literal!
const ELs = document.querySelectorAll("article.wrapper");
const literal = [...ELs].reduce((s,EL) => s + EL.outerHTML,"");
console.log(literal);
<article class="wrapper"><p>Some text 1.</p></article>
<article>No class.</article>
<article class="wrapper"><p>Some text 2.</p></article>
<article>No class.</article>
<article class="wrapper"><p>Some text 3.</p></article>
取决于您实际构建的内容,您需要注意,当从 DOM 中获取项目并将它们转换为字符串时,您可能会丢失任何元素
分配给这些元素的属性或事件(如 "click"
等)。
在这种情况下,您可能只想使用 Element.append(...myNodesList)
将它们移动到 DOM 中所需的新位置:
// Let's say they have some event listeners already assigned:
document.querySelectorAll(".wrapper").forEach(EL => EL.addEventListener("click",(ev) => {
console.log(ev.currentTarget.textContent);
}));
// Get your elements
const ELs = document.querySelectorAll("article.wrapper");
// And simply move them somewhere else!
document.querySelector("#test").append(...ELs);
// Click events are preserved!!
#test { padding: 10px; background: #eee; }
<article class="wrapper"><p>CLICK ME! 1.</p></article>
<article>No class.</article>
<article class="wrapper"><p>CLICK ME! 2.</p></article>
<article>No class.</article>
<article class="wrapper"><p>CLICK ME! 3.</p></article>
<div id="test">
<!-- Let's say you want to insert your .wrapper elements here! -->
</div>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。