我有这两个数组:
var numbers = ['one', 'two', 'three'];
var colors = ['blue', 'red', 'white'];
现在我想要这个输出:
$('.classname').html("<span id = 'one'>blue</span><span id = 'two'>red</span><span id = 'three'>white</span>");
我该怎么做?
我可以使用 join
并将第二个数组与 <span>
混合但我不能添加 id={arr1-values}
:
$('.classname').html('<span>' + colors.join('</span><span>') + '</span>');
最佳答案
如果您想避免 HTML 注入(inject),请不要像那样连接字符串。改用 DOM 方法:
var numbers = ['one', 'two', 'three'],
colors = ['red', 'green', 'blue'],
target = document.querySelector('.classname');
target.innerHTML = ''; // Remove previous contents
numbers.forEach(function(id, i) {
var el = document.createElement('span');
el.id = id;
el.textContent = colors[i];
target.appendChild(el);
});
#one { color: red }
#two { color: green }
#three { color: blue }
<div class="classname"></div>
关于javascript - 如何加入两个数组的值加上它们之间的一些html代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35540528/