我有一个包含JSON数组的外部JS文件,函数可以帮我选择一组随机变量。当我尝试在主HTML文件中生成结果时,p标记中没有显示任何内容。我是不匹配任何对象或变量?
正文部分中HTML文件的简短示例
<p id="result"></p>
<script src="myJSfile.js" type="text/javascript">
<script language="javascript" type="text/javascript">
document.getElementById("result").innerHTML = lottery(selected.name + selected.age);
</script>
外部JS文件的简短示例
function lottery() {
var from, to, selected=new Array();
var person=
[
{"name":"Georgia","age":"45"},
{"name":"John","age":"38"},
{"name":"Michael","age":"29"},
];
if (arguments[0] == "all") {
from=0;
to=person.length;
}
else {
from=Math.floor(Math.random()*3);
to=Math.floor(Math.random()*3+1);
}
for (i=0; i<to; i++) {
selected[i]=person[from];
from=(from+1)%3;
}
return selected;
}
答案 0 :(得分:2)
您的from
,to
和selected
变量在函数外部不可见,只需将此行var from, to, selected=new Array();
移出函数即可。
所有强>
var from, to, selected = new Array();
lottery('all');
for(var k = 0; k < selected.length; k++){
document.getElementById("result").innerHTML += selected[k].name + " " + selected[k].age+'<br />';
}
function lottery() {
var person =
[
{"name":"Georgia","age":"45"},
{"name":"John","age":"38"},
{"name":"Michael","age":"29"},
];
if (arguments[0] == "all") {
from = 0;
to = person.length;
}
else {
from = Math.floor(Math.random()*3);
to = Math.floor(Math.random()*3+1);
}
for (i = 0; i < to; i++) {
selected[i] = person[from];
from = (from+1)%3;
}
return selected;
}
<p id="result"></p>
<强>随机强>
var from, to, selected = new Array();
lottery('all');
for(var k = 0; k < selected.length; k++){
document.getElementById("result").innerHTML += selected[k].name + " " + selected[k].age+'<br />';
}
function lottery() {
var person =
[
{"name":"Georgia","age":"45"},
{"name":"John","age":"38"},
{"name":"Michael","age":"29"},
];
if (arguments[0] == "alla") {
from = 0;
to = person.length;
}
else {
from = Math.floor(Math.random()*3);
to = Math.floor(Math.random()*3+1);
}
for (i = 0; i < to; i++) {
selected[i] = person[from];
from = (from+1)%3;
}
return selected;
}
<p id="result"></p>
答案 1 :(得分:0)
我已对您的代码进行了一些更改,请检查,这应该有效
Monad
并在您的外部js中
<p id="result"></p>
<script src="stackoverflow.js" type="text/javascript">
<script>
(function() {
document.getElementById("result").innerHTML = lottery('all');
})();
</script>