有没有动态的方式在HTML中显示元素?

时间:2016-11-21 18:31:01

标签: javascript html

我有一个数组$短语,其中每个单元格存储一个短语,该短语将显示给用户,或者" ***"表示输入元素将放置在该位置。我附上了一张图片,让自己更清楚。

$phrases[0] = "Lorem ipsum dolor";
$phrases[1] = "***";
$phrases[2] = "consectetur adipiscing elit";
$phrases[3] = "***";
$phrases[4] = "***";
$phrases[5] = "quis nostrud exercitation";

enter image description here

我的问题是:如何让我的代码适应任何给定的数组?

1 个答案:

答案 0 :(得分:2)



var $phrases = [], htmlString = "";
$phrases[0] = "Lorem ipsum dolor";
$phrases[1] = "***";
$phrases[2] = "consectetur adipiscing elit";
$phrases[3] = "***";
$phrases[4] = "***";
$phrases[5] = "quis nostrud exercitation";

for (var i = 0; i < $phrases.length; i++) { //loop through $phrases
  if ($phrases[i] == "***")
    htmlString += "<input type='text'>" //needs input
  else
    htmlString += "<span>" + $phrases[i] + "</span>"; //known value
}

document.getElementById('container').innerHTML = htmlString; //place our htmlString on the page
&#13;
<div id="container"></div>
&#13;
&#13;
&#13;