我有以下div:
<body>
<div id="div0" style="margin-top:5%;text-align:center">
One response will appear here
</div>
</body>
我在脚本标记中有一个数组,只想将array[0]
的值放入div中,以替换它所说的位置&#34;此处将显示一个响应。&#34;
我对div的哪个属性引用此文本感到有点困惑 - 它不是innerHTML或.text
或.textContent
。使用其中任何一个都会引发错误:
&#34;未捕获的TypeError:无法设置属性&lt; innerHTML&#39; of null&#34;
编辑:
这是我从
调用.innerhtml的地方$array=[]
$(document).ready(function(){
$("#button0").click(function(){
$.get("url/here",$("#form0").serialize(), function(response){
$.each(JSON.parse(response), function(index){
$array.push(JSON.parse(response)[index])
});
$("#div0").html($array[0]);
$("#div1").text($array[2]);
document.getElementById("#div2").innerHTML = $array[4];
});
});
});
.html和.text工作得非常好,谢谢大家快速回答。 .innerHTML不起作用,我很好奇为什么会这样?
答案 0 :(得分:3)
如果您使用的是jquery,可以使用以下命令设置div的html:
$(document).ready(function(){
$("#div0").html(array[0]);
}
答案 1 :(得分:2)
你应该展示你的尝试。无论如何,这有效:
document.getElementById('div0').innerHTML = array[0];
如果您不需要HTML,则可以使用textContent
相同的方式:
document.getElementById('div0').textContent = array[0];
根据您收到的错误判断,您的选择器似乎是错误的(或者在代码运行时不可用)。再一次,如果你已经展示了如何做到这一点会更容易。
实例:
var array = ['Hey, this works!'];
document.getElementById('div0').innerHTML = array[0];
<div id="div0" style="margin-top:5%;text-align:center">One response will appear here </div>
答案 2 :(得分:1)
$(document).ready(function(){
$("#div0").html(array[0]);
// or
$("#div0").text(array[0]);
}
您可以使用html()或text()函数
答案 3 :(得分:0)
由于您只是想更新文本,因此您不需要使用innerHTML。只需使用jQuerys文本功能。
<强> HTML 强>
<body>
<div id="div0" style="margin-top:5%;text-align:center">One response will appear here </div>
</body>
<强>的jQuery 强>
$("#div0").text(yourarray[index]);
确保文本存储为数组中的字符串。
答案 4 :(得分:-1)
你可以用jQuery做这样的事情:
$(function() {
var testArray = ["1", "2" ];
var length = testArray.length;
for (var i = 0; i < length; i++) {
var v = testArray[i];
$("#div" + i).text(v);
}
});