输出forEach循环到innerHTML

时间:2018-07-23 16:04:08

标签: javascript ecmascript-6

愚蠢的问题,习惯于使用ES6 / Vanilla JS。

这是与console.log完美配合的循环。...

const theServices = 
      ["Accounting", "Big Data", "Business", "Category", "Concept", "Consultant", "Consumer", "Corporate", "Cost", "Customer", "Development", "Digital", "Distribution", "Due Diligence", "Financial", "Global Sourcing", "Go-to-market", "Growth", "Improvement", "Information", "Technology", "Innovation", "Lean", "Management", "Manufacturing", "Marketing", "Merchandising", "Mergers & Acquisitions", "Operations", "Organization / Organizational", "Performance", "Portfolio", "Post-merger", "Pricing", "Procurement", "Product", "Profitability", "Purchasing", "Restructuring", "Retail", "Revenue", "Sales", "Strategy", "Supply Chain", "Sustainable", "Technology", "Transformation", "Turnaround", "Zero-based", "Budgeting"];


theServices.forEach(function(element) {
    let formName = element;
    formName = formName.replace(/[^A-Za-z0-9]/g, '_').toLowerCase();

console.log( `
<div><input type="checkbox" id="${formName}" name="cpg_services" value="${formName}" />
<label for="${formName}">${element}
</label>
</div>
`)
});
<div id="place-here"></div>

现在尝试使用innerHTML插入DOM返回未定义。输出这样的循环的合适方法是什么?

const theServices = 
      ["Accounting", "Big Data", "Business", "Category", "Concept", "Consultant", "Consumer", "Corporate", "Cost", "Customer", "Development", "Digital", "Distribution", "Due Diligence", "Financial", "Global Sourcing", "Go-to-market", "Growth", "Improvement", "Information", "Technology", "Innovation", "Lean", "Management", "Manufacturing", "Marketing", "Merchandising", "Mergers & Acquisitions", "Operations", "Organization / Organizational", "Performance", "Portfolio", "Post-merger", "Pricing", "Procurement", "Product", "Profitability", "Purchasing", "Restructuring", "Retail", "Revenue", "Sales", "Strategy", "Supply Chain", "Sustainable", "Technology", "Transformation", "Turnaround", "Zero-based", "Budgeting"];


let theseCheckBoxes =
    theServices.forEach(function(element) {
        let formName = element;
        formName = formName.replace(/[^A-Za-z0-9]/g, '_').toLowerCase();

        return `
<div><input type="checkbox" id="${formName}" name="cpg_services" value="${formName}" />
<label for="${formName}">${element}
</label>
</div>
`
    });
;

document.querySelector('#place_here').innerHTML = theseCheckBoxes;
<div id="place_here"></div>

4 个答案:

答案 0 :(得分:3)

ForEach不返回任何内容。因此theseCheckBoxes是不确定的。尝试将其更改为map(),然后将其更改为join()

const theServices = 
      ["Accounting", "Big Data", "Business", "Category", "Concept", "Consultant", "Consumer", "Corporate", "Cost", "Customer", "Development", "Digital", "Distribution", "Due Diligence", "Financial", "Global Sourcing", "Go-to-market", "Growth", "Improvement", "Information", "Technology", "Innovation", "Lean", "Management", "Manufacturing", "Marketing", "Merchandising", "Mergers & Acquisitions", "Operations", "Organization / Organizational", "Performance", "Portfolio", "Post-merger", "Pricing", "Procurement", "Product", "Profitability", "Purchasing", "Restructuring", "Retail", "Revenue", "Sales", "Strategy", "Supply Chain", "Sustainable", "Technology", "Transformation", "Turnaround", "Zero-based", "Budgeting"];


let theseCheckBoxes =
    theServices.map(function(element) {   // <-- map instead of forEach
        let formName = element;
        formName = formName.replace(/[^A-Za-z0-9]/g, '_').toLowerCase();

        return `
<div><input type="checkbox" id="${formName}" name="cpg_services" value="${formName}" />
<label for="${formName}">${element}
</label>
</div>
`
    });
;

document.querySelector('#place_here').innerHTML = theseCheckBoxes.join('\n');
<div id="place_here"></div>

答案 1 :(得分:1)

您不能从forEachreturn a value,但是您可以在迭代时建立html字符串,或者使用map

const theServices = 
      ["Accounting", "Big Data", "Business", "Category", "Concept", "Consultant", "Consumer", "Corporate", "Cost", "Customer", "Development", "Digital", "Distribution", "Due Diligence", "Financial", "Global Sourcing", "Go-to-market", "Growth", "Improvement", "Information", "Technology", "Innovation", "Lean", "Management", "Manufacturing", "Marketing", "Merchandising", "Mergers & Acquisitions", "Operations", "Organization / Organizational", "Performance", "Portfolio", "Post-merger", "Pricing", "Procurement", "Product", "Profitability", "Purchasing", "Restructuring", "Retail", "Revenue", "Sales", "Strategy", "Supply Chain", "Sustainable", "Technology", "Transformation", "Turnaround", "Zero-based", "Budgeting"];


let theseCheckBoxes = "";
    theServices.forEach(function(element) {
        let formName = element;
        formName = formName.replace(/[^A-Za-z0-9]/g, '_').toLowerCase();

        theseCheckBoxes +=`
<div><input type="checkbox" id="${formName}" name="cpg_services" value="${formName}" />
<label for="${formName}">${element}
</label>
</div>
`
    });
;

document.querySelector('#place_here').innerHTML = theseCheckBoxes;
<div id="place_here"></div>

答案 2 :(得分:1)

而不是返回(自forEach returns undefined起),将html附加到字符串let str = ''上,然后将字符串放入div中。像这样:

const theServices = ["Accounting", "Big Data", "Business", "Category", "Concept", "Consultant", "Consumer", "Corporate", "Cost", "Customer", "Development", "Digital", "Distribution", "Due Diligence", "Financial", "Global Sourcing", "Go-to-market", "Growth", "Improvement", "Information", "Technology", "Innovation", "Lean", "Management", "Manufacturing", "Marketing", "Merchandising", "Mergers & Acquisitions", "Operations", "Organization / Organizational", "Performance", "Portfolio", "Post-merger", "Pricing", "Procurement", "Product", "Profitability", "Purchasing", "Restructuring", "Retail", "Revenue", "Sales", "Strategy", "Supply Chain", "Sustainable", "Technology", "Transformation", "Turnaround", "Zero-based", "Budgeting"];

let str = ''

theServices.forEach(function(element) {
  let formName = element;
  formName = formName.replace(/[^A-Za-z0-9]/g, '_').toLowerCase();

  str += `<div>
            <input type="checkbox" id="${formName}" name="cpg_services" value="${formName}" />
            <label for="${formName}">${element}</label>
          </div>`
});

document.querySelector('#place_here').innerHTML = str;
<div id="place_here"></div>

答案 3 :(得分:1)

我想添加另一个解决方案,那就是使用reduce将数组缩小为这样的字符串:

const theServices = ["Accounting", "Big Data", "Business", "Category", "Concept", "Consultant", "Consumer", "Corporate", "Cost", "Customer", "Development", "Digital", "Distribution", "Due Diligence", "Financial", "Global Sourcing", "Go-to-market", "Growth", "Improvement", "Information", "Technology", "Innovation", "Lean", "Management", "Manufacturing", "Marketing", "Merchandising", "Mergers & Acquisitions", "Operations", "Organization / Organizational", "Performance", "Portfolio", "Post-merger", "Pricing", "Procurement", "Product", "Profitability", "Purchasing", "Restructuring", "Retail", "Revenue", "Sales", "Strategy", "Supply Chain", "Sustainable", "Technology", "Transformation", "Turnaround", "Zero-based", "Budgeting"];

let str = theServices.reduce(function(str, element) {
  let formName = element;
  formName = formName.replace(/[^A-Za-z0-9]/g, '_').toLowerCase();

  return str.concat(`<div>
            <input type="checkbox" id="${formName}" name="cpg_services" value="${formName}" />
            <label for="${formName}">${element}</label>
          </div>`)
}, '');

document.querySelector('#place_here').innerHTML = str;
<div id="place_here"></div>