我目前正在制作一个您喜欢或不喜欢屏幕上显示的活动的程序。我的问题:我想在单击拇指按下输入或点击竖起大拇指输入后随机生成的单词更改。
这是我的Javascript代码:
let words = ['Food', 'Video Games', 'Movies', 'Spa', 'Sleeping'];
let word = words[Math.floor(Math.random()*words.length)];
document.getElementById("word").innerHTML = word;
function ai(){
document.getElementById("liked").innerHTML = "LIKED";
document.getElementById("disliked").innerHTML = "";
}
function aii(){
document.getElementById("disliked").innerHTML = "DISLIKED";
document.getElementById("liked").innerHTML = "";
}
这是我的HTML代码:
<h1 id="word"></h1>
<h1 id="liked"></h1>
<h1 id="disliked"></h1>
<input type="image" src="thumbsup.png" class="tu" onclick="ai()">
<input type="image" src="thumbsdown.png" class="td" onclick="aii()">
提前致谢!
答案 0 :(得分:0)
将随机生成移动到函数中。您可以创建一个执行随机生成的函数,然后在您的onclick函数中调用该函数
let words = ['Food', 'Video Games', 'Movies', 'Spa', 'Sleeping'];
function random_generate(){
let word = words[Math.floor(Math.random()*words.length)];
document.getElementById("word").innerHTML = word;
}
function ai(){
random_generate();
document.getElementById("liked").innerHTML = "LIKED";
document.getElementById("disliked").innerHTML = "";
}
function aii(){
random_generate();
document.getElementById("disliked").innerHTML = "DISLIKED";
document.getElementById("liked").innerHTML = "";
}
<h1 id="word"></h1>
<h1 id="liked"></h1>
<h1 id="disliked"></h1>
<input type="image" src="thumbsup.png" class="tu" onclick="ai()">
<input type="image" src="thumbsdown.png" class="td" onclick="aii()">
答案 1 :(得分:0)
只需将随机单词生成为函数,
function generate_random() {
let word = words[Math.floor(Math.random()*words.length)];
document.getElementById("word").innerHTML = word;
}
然后在脚本开头或构造函数中调用此函数(取决于您正在使用的框架),然后在ai()和aii()中添加函数调用
function ai(){
document.getElementById("liked").innerHTML = "LIKED";
document.getElementById("disliked").innerHTML = "";
generate_random();
}
function aii(){
document.getElementById("disliked").innerHTML = "DISLIKED";
document.getElementById("liked").innerHTML = "";
generate_random();
}
答案 2 :(得分:0)
您只在声明中选择一个随机单词,只更改文字onClick
。
你应该创建一个函数来选择随机单词onClick
,如下所示:
const pickWord = () => words[Math.floor(Math.random()*words.length)];
function ai(){
document.getElementById("liked").innerHTML = "LIKED";
document.getElementById("disliked").innerHTML = "";
document.getElementById("word").innerHTML = pickWord();
}