如何将JS数组中的每个元素转换为独立的HTML元素?
It looks like the main issue with your current code is how you're building the HTML string for moreInfo. Right now, you're using the entire info array as part of the separator in join(), which is causing the full array content to be inserted between each element instead of wrapping each individual item in a <span>. Here's the corrected approach:
Corrected JavaScript Code
function onChange(e) { var selected = this.select()[0], item = this.dataItem(selected); var info = [item.LeadID, item.Subject, item.Email, item.Phone]; // Wrap each array element in a span, then combine into one string var moreInfo = info.map(entry => `<span>${entry}</span>`).join(''); document.getElementById("moreInfo").innerHTML = moreInfo; }
Breakdown of the Fix:
Array.map(): This loops through every item in yourinfoarray and converts each one into a string wrapped in<span>tags. For example,item.LeadID(which is 211 in your sample) becomes<span>211</span>.join(''): This takes all those span strings and sticks them together into a single HTML snippet without any extra characters between them.
What This Produces
When you run this with your sample data, it will generate exactly the HTML structure you're aiming for:
<div id="moreInfo"> <span>211</span> <span>Re: Energy Transfer</span> <span>evelyn.adams@sampleemail.com</span> <span>0457767890</span> </div>
If you want the generated HTML to have each span on its own line (like your sample), just add a newline character in the mapped string:
var moreInfo = info.map(entry => `<span>${entry}</span>\n`).join('');
This doesn't change how the page renders—it just makes the HTML source code easier to read.
内容的提问来源于stack exchange,提问作者codeflower

