javascript - 试图将我的 javascript 链接到一个按钮

标签 javascript css

我是 JavaScript 的新手,我正在尝试弄清楚如何将我拥有的按钮链接到我的功能。该代码是某种随机化器,所以本质上我是在尝试将按钮连接到我的代码,以便您可以按随机顺序点击不同的元素。

在尝试了很多不同的东西后,我似乎无法让它工作。

非常感谢任何帮助。

 <div class="container">
    <div class="card fade-in">
        <p id="randomStrategy"></p>

        <script>

        // Establish a variable, which pulls from an array.

        var selectStrategy = [

        "Abandon desire",
        "Abandon normal instructions",
        "Accept advice",
        "Adding on",
        "A line has two sides",
        "Always the first steps",
        "Ask people to work against their better judgement",
        "Ask your body",
        "Be dirty",
        "Be extravagant",
        "Be less critical",
        "Breathe more deeply",
        "Bridges -build -burn",
        "Change ambiguities to specifics",
        "Change nothing and continue consistently",
        "Change specifics to ambiguities",
        "Consider transitions",
        "Courage!",
        "Cut a vital connection",
        "Decorate, decorate",
        "Destroy nothing; destroy the most important thing",
        "Discard an axiom",
        "Disciplined self-indulgence",
        "Discover your formulas and abandon them",
        "Display your talent",
        "Distort time",
        "Do nothing for as long as possible",
        "Don’t avoid what is easy",
        "Don’t break the silence",
        "Don’t stress one thing more than another",
        "Do something boring",
        "Do something sudden, destructive and unpredictable",
        "Do the last thing first",
        "Do the words need changing?",
        "Emphasise differences",
        "Emphasise the flaws",
        "Faced with a choice, do both (From Dieter Rot.)",
        "Find a safe part and use it as an anchor",
        "Give the game away",
        "Give way to your worst impulse",
        "Go outside. Shut the door.",
        "Go to an extreme, come part way back",
        "How would someone else do it?",
        "How would you have done it?",
        "In total darkness, or in a very large room, very quietly",
        "Is it finished?",
        "Is something missing?",
        "Is the style right?",
        "It is simply a matter or work",
        "Just carry on",
        "Listen to the quiet voice",
        "Look at the order in which you do things",
        "Magnify the most difficult details",
        "Make it more sensual",
        "Make what’s perfect more human",
        "Move towards the unimportant",
        "Not building a wall; making a brick",
        "Once the search has begun, something will be found",
        "Only a part, not the whole",
        "Only one element of each kind",
        "Openly resist change",
        "Pae White’s non-blank graphic metacard",
        "Question the heroic approach",
        "Remember quiet evenings",
        "Remove a restriction",
        "Repetition is a form of change",
        "Retrace your steps",
        "Reverse",
        "Simple Subtraction",
        "Slow preparation, fast execution",
        "State the problem as clearly as possible",
        "Take a break",
        "Take away the important parts",
        "The inconsistency principle",
        "The most easily forgotten thing is the most important",
        "Think -inside the work -outside the work",
        "Tidy up",
        "Try faking it (From Stewart Brand.)",
        "Turn it upside down",
        "Use an old idea",
        "Use cliches",
        "Use filters",
        "Use something nearby as a model",
        "Use ‘unqualified’ people",
        "Use your own ideas",
        "Voice your suspicions",
        "Water",
        "What context would look right?",
        "What is the simplest solution?",
        "What mistakes did you make last time?",
        "What to increase? What to reduce? What to maintain?",
        "What were you really thinking about just now?",
        "What wouldn’t you do?",
        "What would your closest friend do?",
        "When is it for?",
        "Where is the edge?",
        "Which parts can be grouped?",
        "Work at a different speed",
        "Would anyone want it?",
        "Your mistake was a hidden intention",
        "Use fewer notes",
        "Use filters",
        "Use ‘unqualified’ people",
        "Water",
        "What are you really thinking about just now? Incorporate",
        "What is the reality of the situation?",
        "What mistakes did you make last time?",
        "What would your closest friend do?",
        "What wouldn’t you do?",
        "Work at a different speed",
        "You are an engineer",
        "You can only make one dot at a time",
        "You don’t have to be ashamed of using your own ideas",
        // The following is where the randomness magic happens. 
        ];
        var pickAStrategy = function () {
        var randomStrategy = selectStrategy[Math.floor(Math.random() * selectStrategy.length)];
        return randomStrategy;
        };
        // This writes the strategy to the page.

        document.getElementById("randomStrategy").innerHTML = pickAStrategy();
        </script>

        <INPUT TYPE=BUTTON VALUE="Click Me" onClick="pickAStrategy(document.randomStrategy);" id="button"></INPUT>

    </div> <!-- /card -->
</div> <!-- /container -->

最佳答案

我的回答太慢了 - 但展示了评论和其他答案中的内容,例如 istrupin 的 “onClick="pickAStrategy() 不应该采用任何参数。”,并应用一些更好的做法,我想到了这个。
我还重命名了一些内容,以便更容易看出名称之间的区别。

首先,简化您的页面结构——从中提取代码(关注点分离)

<div class="container">
    <div class="card fade-in">
        <p id="randomStrategy"></p>
        <input type="button" id="pickrandom" value="Click Me">
    </div> <!-- /card -->
</div> <!-- /container -->

请注意按钮上没有 onClick=。更好的做法是使用代码本身附加事件的处理程序,例如

document.getElementById('pickrandom').addEventListener('click', pickAStrategy);

pickAStrategy 函数可以设置p id="randomStrategy" 本身的内容,所以不需要返回任何东西。这将提供以下脚本 block ,您可以将其放在页面标记的末尾。 (直到您学会在“DOM 准备就绪”时附加代码)

<script>
document.getElementById('pickrandom').addEventListener('click', pickAStrategy);

function pickAStrategy()
{
    var chosenStrategy = strategies[Math.floor(Math.random() * strategies.length)];
    //console.log('chosen: ' + chosenStrategy);
    document.getElementById('randomStrategy').innerHTML = chosenStrategy;
}

var strategies = [ ... ];
</script>

将所有这些放在一起,并添加一些样式以便您可以在填充之前查看 randomStrategy 的位置,给出此代码 as seen in this fiddle :

<style>
p#randomStrategy {
    min-height: 14px;
    min-width: 23px;
    border: 1px dotted green;
}
</style>

<div class="container">
    <div class="card fade-in">
        <p id="randomStrategy"></p>
        <input type="button" id="pickrandom" value="Click Me">
    </div> <!-- /card -->
</div> <!-- /container -->


<script>
document.getElementById('pickrandom').addEventListener('click', pickAStrategy);

function pickAStrategy()
{
    var chosenStrategy = strategies[Math.floor(Math.random() * strategies.length)];
    //console.log('chosen: ' + chosenStrategy);
    document.getElementById('randomStrategy').innerHTML = chosenStrategy;
}

var strategies = [
    "Abandon desire",
    "Abandon normal instructions",
    "Accept advice",
    "Adding on",
    "A line has two sides",
    "Always the first steps",
    "Ask people to work against their better judgement",
    "Ask your body",
    "Be dirty",
    "Be extravagant",
    "Be less critical",
    "Breathe more deeply",
    "Bridges -build -burn",
    "Change ambiguities to specifics",
    "Change nothing and continue consistently",
    "Change specifics to ambiguities",
    "Consider transitions",
    "Courage!",
    "Cut a vital connection",
    "Decorate, decorate",
    "Destroy nothing; destroy the most important thing",
    "Discard an axiom",
    "Disciplined self-indulgence",
    "Discover your formulas and abandon them",
    "Display your talent",
    "Distort time",
    "Do nothing for as long as possible",
    "Don’t avoid what is easy",
    "Don’t break the silence",
    "Don’t stress one thing more than another",
    "Do something boring",
    "Do something sudden, destructive and unpredictable",
    "Do the last thing first",
    "Do the words need changing?",
    "Emphasise differences",
    "Emphasise the flaws",
    "Faced with a choice, do both (From Dieter Rot.)",
    "Find a safe part and use it as an anchor",
    "Give the game away",
    "Give way to your worst impulse",
    "Go outside. Shut the door.",
    "Go to an extreme, come part way back",
    "How would someone else do it?",
    "How would you have done it?",
    "In total darkness, or in a very large room, very quietly",
    "Is it finished?",
    "Is something missing?",
    "Is the style right?",
    "It is simply a matter or work",
    "Just carry on",
    "Listen to the quiet voice",
    "Look at the order in which you do things",
    "Magnify the most difficult details",
    "Make it more sensual",
    "Make what’s perfect more human",
    "Move towards the unimportant",
    "Not building a wall; making a brick",
    "Once the search has begun, something will be found",
    "Only a part, not the whole",
    "Only one element of each kind",
    "Openly resist change",
    "Pae White’s non-blank graphic metacard",
    "Question the heroic approach",
    "Remember quiet evenings",
    "Remove a restriction",
    "Repetition is a form of change",
    "Retrace your steps",
    "Reverse",
    "Simple Subtraction",
    "Slow preparation, fast execution",
    "State the problem as clearly as possible",
    "Take a break",
    "Take away the important parts",
    "The inconsistency principle",
    "The most easily forgotten thing is the most important",
    "Think -inside the work -outside the work",
    "Tidy up",
    "Try faking it (From Stewart Brand.)",
    "Turn it upside down",
    "Use an old idea",
    "Use cliches",
    "Use filters",
    "Use something nearby as a model",
    "Use ‘unqualified’ people",
    "Use your own ideas",
    "Voice your suspicions",
    "Water",
    "What context would look right?",
    "What is the simplest solution?",
    "What mistakes did you make last time?",
    "What to increase? What to reduce? What to maintain?",
    "What were you really thinking about just now?",
    "What wouldn’t you do?",
    "What would your closest friend do?",
    "When is it for?",
    "Where is the edge?",
    "Which parts can be grouped?",
    "Work at a different speed",
    "Would anyone want it?",
    "Your mistake was a hidden intention",
    "Use fewer notes",
    "Use filters",
    "Use ‘unqualified’ people",
    "Water",
    "What are you really thinking about just now? Incorporate",
    "What is the reality of the situation?",
    "What mistakes did you make last time?",
    "What would your closest friend do?",
    "What wouldn’t you do?",
    "Work at a different speed",
    "You are an engineer",
    "You can only make one dot at a time",
    "You don’t have to be ashamed of using your own ideas",
    // The following is where the randomness magic happens. 
    ];
</script>

关于javascript - 试图将我的 javascript 链接到一个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43666444/

相关文章:

html - CSS - 无法按类更改占位符颜色

javascript - 使用其 src 在 javascript 中隐藏图像

javascript - 如何将javascript排入wordpress子主题

javascript - 如何使用javascript更改图像文件名

html - 当span用于包含一个&lt;input type ="text">时,为什么span默认设计成宽度小于其父元素的宽度

html - 将图片指向一行文本

javascript - Angular 用户界面 - 选择 : tagging without multiple - why isn't this working?

javascript - UI 选择的对象源

html - 使用 flexbox 创建导航栏时如何避免右侧出现额外空间(justify-content : space-between/around) properties

css - 帮助进行 CSS 布局