我想问一下如何在拆分后为每个数组分配一个固定的id。让我做一下解释,$ output是从数据库中检索到的句子,“我#爱#读书。”。这实际上意味着我在下面的代码中使用的分隔符是“#”,所以允许句子分割。所以现在我想问一下如何为每个拆分元素分配修复ID。这意味着“我”将是id1,“爱”将是id2,“阅读书籍”将是id3。我怎样才能做到这一点?我不希望它被硬编码,因为整个句子是从数据库中检索的。我想让它拆分并为每个元素分配。
<script>
var js_var = "<?php echo $output ?>";
var div_id = ['id1','id2','id3','id4','id5','id6','id7','id8','id9','id10'];
var box_id = ['box1','box2','box3','box4','box5','box6','box7','box8','box9','box10'];
var original = js_var.split("#");
var balls90= js_var.split("#");
var x = document.getElementById("demo");
x.innerHTML = balls90.join(" ");
</script>
答案 0 :(得分:0)
您可以使用简单的for
循环轻松完成,下面是代码:
var js_var = "<?php echo $output ?>";
var div_id = ['id1','id2','id3','id4','id5','id6','id7','id8','id9','id10'];
var box_id = ['box1','box2','box3','box4','box5','box6','box7','box8','box9','box10'];
var original = js_var.split("#");
var balls90= js_var.split("#");
var x = document.getElementById("demo");
// I assume you want to use the balls90 variable
// and you want to add the divs to the #demo element
for (var i=0; i < balls90.length; i++) {
var el = document.createElement('div');
el.id = div_id[i];
el.innerHTML = balls90[i];
x.appendChild(el);
}
然后你的HTML代码会变成这样:
<div id="demo">
<div id="id1">I</div>
<div id="id2">love to</div>
<div id="id3">read books</div>
</div>