2016-04-28 189 views
0

我已经成功地根据数组中基于点击按钮的对象值创建了一个随机语句生成器。我无法弄清楚的是,如何在每次点击按钮时创建一个新句子。 似乎我可以只清除#output的内容,当按钮被点击时,randomWord()会再次运行但没有骰子。每次点击一个按钮创建新的随机句子

var words = { 
    noun : ['mouse','bird','cat','dog'], 
    verb : ['runs','sleeps','explodes','flies'], 
    place : ['house', 'space station', 'car', 'office'] 
    }; 

var container = document.getElementById('output'); 
    function print(sentence){ 
    container.innerHTML = sentence; 
} 

var noun; 
var verb; 
var place; 

var word; 
var sentence; 
var button; 

function randomWord(type){ 
    rando = Math.floor(Math.random() * words[type].length); 
    word = words[type][rando]; 
    return word; 
} 

noun = randomWord('noun'); 
verb = randomWord('verb'); 
place = randomWord('place'); 

$('button').click(function(){ 
    $('#output ').empty(); 
    var sentence = "<p>The " + noun + " " + verb + " in the " + place + ".</p>"; 
    print(sentence); 
}); 

Codepen

+1

在您的点击功能中移动按钮方法上方的3行。 – fix

回答

1

你需要点击按钮后,每次更新您的随机变量,目前你一旦脚本在初始化过程中这样做:

$('button').click(function(){ 
    $('#output ').empty(); 

    //generate new random words on click 
    noun = randomWord('noun'); 
    verb = randomWord('verb'); 
    place = randomWord('place'); 

    var sentence = "<p>The " + noun + " " + verb + " in the " + place + ".</p>"; 
    print(sentence); 
}); 
+0

啊,谢谢!我只是明显地学习。 – lowbelly

0

也许你只需要尝试:

$('button').click(function(){ 
     noun = randomWord('noun'); 
     verb = randomWord('verb'); 
     place = randomWord('place'); 

     var sentence = "<p>The " + noun + " " + verb + " in the " + place + ".</p>"; 
     print(sentence); 
    }); 
+0

这样做,谢谢! – lowbelly

1

几件事:

  • id引用输出有一个额外的空间

    $( '#输出 ').empty()===> $(' #输出')空();

  • 您可能希望从jQuery的

  • 而像其他的答案说,你需要在点击动作

快速测试这里的随机呼叫使用文档就绪:

<html> 

<script src="https://code.jquery.com/jquery-2.2.3.min.js" ></script> 
<script> 

$(document).ready(function() { 


var words = { 
    noun : ['mouse','bird','cat','dog'], 
    verb : ['runs','sleeps','explodes','flies'], 
    place : ['house', 'space station', 'car', 'office'] 
}; 

var container = document.getElementById('output'); 

function print(sentence){ 
    container.innerHTML = sentence; 
} 

var noun; 
var verb; 
var place; 

var word; 
var sentence; 
var button; 

function randomWord(type){ 
    rando = Math.floor(Math.random() * words[type].length); 
    word = words[type][rando]; 
    return word; 
} 

$('#button').click(function(){ 

    noun = randomWord('noun'); 
    verb = randomWord('verb'); 
    place = randomWord('place'); 

    $('#output').empty(); 
    var sentence = "<p>The " + noun + " " + verb + " in the " + place + ". </p>"; 
    print(sentence); 
}); 

}); 
</script> 
<div id="output"></div> 

<button id="button">click</button> 

</html> 
相关问题