需要 JavaScript 帮助(YQL 和 JavaScript)
我有这个“改编”的JavaScript代码来显示任何事情的有趣事实(在本例中是关于电影和/或历史) 然而,它一次只显示一个事实,用户需要按一个按钮才能显示另一个事实。
我的问题是,有没有一种方法可以一次显示所有事实,而不是一次只显示一个事实?
function funfacts(o){
var facts = document.getElementById('funfacts');
facts.className = 'js';
if(facts){
var data = o.query.results.p;
var link = facts.getElementsByTagName('a')[0];
link.innerHTML = '(see all facts)';
var out = document.createElement('p');
out.className = 'fact';
facts.insertBefore(out,link.parentNode);
function seed(){
var ran = parseInt(Math.random()*data.length);
out.innerHTML = data[ran];
}
var b = document.createElement('button');
b.innerHTML = 'get another fact';
b.onclick = seed;
link.parentNode.insertBefore(b,link);
seed();
}
}
<script src="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D'http%3A%2F%2Fwww.tealdragon.net%2Fhumor%2Ffacts%2Ffacts.htm'%20and%20xpath%3D'%2F%2Fli%2Fp'&format=json&diagnostics=true&callback=funfacts"></script>
I have this "adapted" javascript code to display funfacts about anything (in this case about movies and/or History)
However, it is built to display only one fact at a time, the user needs to press a button to display another funfact.
My question is, is there a way to display all the facts at once and not just one at a time?
function funfacts(o){
var facts = document.getElementById('funfacts');
facts.className = 'js';
if(facts){
var data = o.query.results.p;
var link = facts.getElementsByTagName('a')[0];
link.innerHTML = '(see all facts)';
var out = document.createElement('p');
out.className = 'fact';
facts.insertBefore(out,link.parentNode);
function seed(){
var ran = parseInt(Math.random()*data.length);
out.innerHTML = data[ran];
}
var b = document.createElement('button');
b.innerHTML = 'get another fact';
b.onclick = seed;
link.parentNode.insertBefore(b,link);
seed();
}
}
<script src="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D'http%3A%2F%2Fwww.tealdragon.net%2Fhumor%2Ffacts%2Ffacts.htm'%20and%20xpath%3D'%2F%2Fli%2Fp'&format=json&diagnostics=true&callback=funfacts"></script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
变量
data
包含数组中的所有事实。当用户单击时,函数seed
会从数组中随机选择一项。因此,要显示全部内容:
这会将事实连接到单个字符串中,并用换行符分隔。
编辑添加:
这是一个完整、非常简单的网页示例,显示所有项目:
The variable
data
contains all of the facts in an array. When the user clicks, the functionseed
is randomly selecting one item out of the array.So, to display them all:
This joins the facts into a single string, separated by newlines.
Edited to add:
Here's an example of a complete, very simple web page that displays all of the items: