如何使按钮可重复使用?

时间:2013-09-05 02:30:09

标签: javascript html button

我对编程世界相对较新。我对HTML和CSS有很强的了解,最近又学会了JavaScript。我正在研究一系列文本生成器作为学校项目;我的目标是能够在网站上单击按钮,让计算机在每次单击按钮时随机吐出文本。然而,虽然我对HTML和JavaScript有很好的把握,但我对如何将两者结合起来提供网页功能的知识几乎不存在。

我使用JavaScript创建了一个“Shakespearean Insult Generator”,它是有用的,我想出了如何在页面上添加一个按钮,这样当你点击按钮时,它会打印一个随机生成的页面侮辱:

<script>
var adjective1 = ["artless", "bawdy", "beslubbering"...
var adjective2 = ["base-court", "bat-fowling", "beef-witted"...
var noun = ["apple-john", "baggage", "barnacle"...

var insult = "Thou art a " + adjective1[Math.floor(Math.random() * 60)] + ", " + adjective2[Math.floor(Math.random() * 60)] + ", " + noun[Math.floor(Math.random() * 60)] + "!";

var genInsult = function() {
x=document.getElementById("replace");  
x.innerHTML=insult;    
};
</script>

<p id= "replace">Your insult will appear here!</p>
<button type="button" onclick="genInsult()">Generate Insult</button>

然而,一旦按下按钮一次,除非刷新页面,否则不能再次按此按钮以产生另一种侮辱。

所以我的问题是:如何使用JavaScript重新使用此按钮?

我试过寻找我的问题的答案,但问题是我对JavaScript很陌生,以至于我常常无法理解其他人的问题及其答案。此外,很多回复都引用了jQuery,这是一种我不知道的语言。如果有人在JavaScript领域有解决方案,我将非常感激!

我现在可能不知道很多,但我非常渴望学习!

2 个答案:

答案 0 :(得分:3)

移动它:

var insult = "Thou art a " + adjective1[Math.floor(Math.random() * 60)] + ", " + adjective2[Math.floor(Math.random() * 60)] + ", " + noun[Math.floor(Math.random() * 60)] + "!";

在你的genInsult()功能中,你应该是好的。现在它在外面所以它只会产生一次。

答案 1 :(得分:0)

正如已经说过的那样,你的主要问题只是侮辱的创建超出了你的功能,所以它只创建一次,而不是每次调用函数。我真的很喜欢重新分解代码,我想提供给你:(click here for live demo)

我使用面向对象的模式编写了您的应用程序,并清理了大量混乱和低效率。我认为学习这个并且学到所有你能做的很好!顺便说一下,除非你使用的是一个理解它的框架(比如AngularJS),否则不要使用内联javascript(你的html中的click函数)。

<p id="insult">Your insult will appear here!</p>
<button type="button" id="generate">Generate Insult</button>

和js:

var generator = { //only one global variable!!
  init: function() { //this sets up your app for use
    var elem = document.getElementById('insult');

    var obj = this; //cache reference to the generator object (the "this" pointer will be changed within the click function
    var button = document.getElementById('generate');
    button.addEventListener('click', function() {
      elem.innerText = obj.generateInsult();
    });
  },
  generateInsult: (function() { //use an IIFE to give a nice closure to these variables
    var generateInsult = function() {
      return "Thou art a "+adjs1[r(adjs1)]+", "+adjs2[r(adjs2)]+", "+nouns[r(nouns)]+"!";
    };
    function r(arr) {
      return Math.floor(Math.random() * arr.length); 
    }
    var adjs1 = ["artless", "bawdy", "beslubbering"];
    var adjs2 = ["base-court", "bat-fowling", "beef-witted"];
    var nouns = ["apple-john", "baggage", "barnacle"];
    return generateInsult;
  }())
};

generator.init(); //I suggest running this on document ready to be sure the elements are loaded. If not, this will not work. Keep that in mind!
相关问题