简体   繁体   中英

Is it possible to combine document.ready function and a button click function?

I am attempting to write a random tavern name generator, and would like the names to be ready when the document loads, and for a button click to generate a new name.

I am wondering if I am able to combine this document.ready function:

    $(document).ready(function(){
      var W = randomWord('W'),
        W2 = randomWord('W'),
        X = randomWord('X'),
        Y = randomWord('Y'),
        Y2 = randomWord('Y'),
        Z = randomWord('Z');
      var names = ['The ' + W + ' & ' + W2 + ' ', 'The ' + X + ' ' + W + ' ', 'The ' + W + "'s " + Y + ' ', 'The ' + Z + ' ' + W + ' ', 'The ' + Y + ' & ' + Y2 + ' ', 'The ' + W + " & " + Y + ' ', 'The ' + Z + ' ' + Y + ' ', 'The ' + X + ' ' + Y + ' '];
      var name = names[Math.floor(Math.random() * names.length)];
      var container = document.getElementById('output');
      container.innerHTML = name;
    });

with my button click function:

$('.button').click(function() {
  var W = randomWord('W'),
    W2 = randomWord('W'),
    X = randomWord('X'),
    Y = randomWord('Y'),
    Y2 = randomWord('Y'),
    Z = randomWord('Z');
  var names = ['The ' + W + ' & ' + W2 + ' ', 'The ' + X + ' ' + W + ' ', 'The ' + W + "'s " + Y + ' ', 'The ' + Z + ' ' + W + ' ', 'The ' + Y + ' & ' + Y2 + ' ', 'The ' + W + " & " + Y + ' ', 'The ' + Z + ' ' + Y + ' ', 'The ' + X + ' ' + Y + ' '];
  var name = names[Math.floor(Math.random() * names.length)];
  var container = document.getElementById('output');
  container.innerHTML = name;

They are the same function, but with two different triggers.

Can I do something like...?

    $(document).ready(function(), $('.button').click(function(){
codecodecode
});

Thank you!

(for testing purposes, the entire code is : https://jsfiddle.net/mpqf68tg/ )

<div style="width: 100%; text-align: center;">
  <h2 style="font-size:  48pt; font-family: Fredericka the Great;" id="output" class="button">&nbsp;</h2>
</div>

<script>
    var words = {
      W: ['ace', 'axman', 'archer', 'ale', 'bastard', 'dragon', 'badger', 'ax', 'blade', 'fool', 'battlement', 'bear', 'bull', 'hawk', 'bridge', 'bee', 'cat', 'highwayman', 'brook', 'boar', 'cock', 'hound', 'castle', 'duke', 'dog', 'idiot', 'city', 'dutchess', 'hammer', 'mage', 'clock', 'fire', 'jack', 'manticore', 'deer', 'fish', 'king', 'mare', 'eagle', 'flag', 'knife', 'mouse', 'goat', 'lion', 'ladies', 'prince', 'mace', 'mole', 'maiden', 'princess', 'mule', 'mountain', 'nightmare', 'ram', 'potion', 'nymph', 'plough', 'man', 'rat', 'river', 'sea', 'queen', 'snake', 'shark', 'ship', 'rogue', 'sorrow', 'shield', 'trap', 'sow', 'sword', 'soldier', 'virgin', 'swallow', 'widow', 'tree', 'wasp', 'wizards', 'wyrm', 'village', 'wolf'],
      X: ['belching', 'crushing', 'dreaming', 'drinking', 'drowning', 'fighting', 'laughing', 'laying', 'living', 'plotting', 'prancing', 'running', 'screaming', 'singing', 'sleeping', 'sneaking', 'snoozing', 'stabbing', 'starving', 'swinging'],
      Y: ['cart', 'child', 'cup', 'dream', 'flagon', 'folly', 'fork', 'hearth', 'husband', 'inn', 'keep', 'knife', 'mug', 'nightmare', 'plate', 'plot', 'song', 'spoon', 'wagon', 'wife'],
      Z: ['bloodied', 'branded', 'bronzed', 'burnt', 'chipped', 'cracked', 'dropped', 'drowned', 'fallen', 'forgotten', 'frozen', 'full', 'half', 'quarter', 'rusted', 'soaked', 'spun', 'stabbed', 'tall', 'thirsty']
    };
    function randomWord(type) {
      var rando = Math.floor(Math.random() * words[type].length),
        word = words[type][rando];
      return word;
    }
    $(document).ready(function(){
      var W = randomWord('W'),
        W2 = randomWord('W'),
        X = randomWord('X'),
        Y = randomWord('Y'),
        Y2 = randomWord('Y'),
        Z = randomWord('Z');
      var names = ['The ' + W + ' & ' + W2 + ' ', 'The ' + X + ' ' + W + ' ', 'The ' + W + "'s " + Y + ' ', 'The ' + Z + ' ' + W + ' ', 'The ' + Y + ' & ' + Y2 + ' ', 'The ' + W + " & " + Y + ' ', 'The ' + Z + ' ' + Y + ' ', 'The ' + X + ' ' + Y + ' '];
      var name = names[Math.floor(Math.random() * names.length)];
      var container = document.getElementById('output');
      container.innerHTML = name;

    });
    $('.button').click(function(){
      var W = randomWord('W'),
        W2 = randomWord('W'),
        X = randomWord('X'),
        Y = randomWord('Y'),
        Y2 = randomWord('Y'),
        Z = randomWord('Z');
      var names = ['The ' + W + ' & ' + W2 + ' ', 'The ' + X + ' ' + W + ' ', 'The ' + W + "'s " + Y + ' ', 'The ' + Z + ' ' + W + ' ', 'The ' + Y + ' & ' + Y2 + ' ', 'The ' + W + " & " + Y + ' ', 'The ' + Z + ' ' + Y + ' ', 'The ' + X + ' ' + Y + ' '];
      var name = names[Math.floor(Math.random() * names.length)];
      var container = document.getElementById('output');
      container.innerHTML = name;

    });
</script>

I'd suggest putting your code into a function since you need to use it multiple times. The first instance runs when the page loads, then you can bind the second to a click event.

 var words = { W: ['ace', 'axman', 'archer', 'ale', 'bastard', 'dragon', 'badger', 'ax', 'blade', 'fool', 'battlement', 'bear', 'bull', 'hawk', 'bridge', 'bee', 'cat', 'highwayman', 'brook', 'boar', 'cock', 'hound', 'castle', 'duke', 'dog', 'idiot', 'city', 'dutchess', 'hammer', 'mage', 'clock', 'fire', 'jack', 'manticore', 'deer', 'fish', 'king', 'mare', 'eagle', 'flag', 'knife', 'mouse', 'goat', 'lion', 'ladies', 'prince', 'mace', 'mole', 'maiden', 'princess', 'mule', 'mountain', 'nightmare', 'ram', 'potion', 'nymph', 'plough', 'man', 'rat', 'river', 'sea', 'queen', 'snake', 'shark', 'ship', 'rogue', 'sorrow', 'shield', 'trap', 'sow', 'sword', 'soldier', 'virgin', 'swallow', 'widow', 'tree', 'wasp', 'wizards', 'wyrm', 'village', 'wolf'], X: ['belching', 'crushing', 'dreaming', 'drinking', 'drowning', 'fighting', 'laughing', 'laying', 'living', 'plotting', 'prancing', 'running', 'screaming', 'singing', 'sleeping', 'sneaking', 'snoozing', 'stabbing', 'starving', 'swinging'], Y: ['cart', 'child', 'cup', 'dream', 'flagon', 'folly', 'fork', 'hearth', 'husband', 'inn', 'keep', 'knife', 'mug', 'nightmare', 'plate', 'plot', 'song', 'spoon', 'wagon', 'wife'], Z: ['bloodied', 'branded', 'bronzed', 'burnt', 'chipped', 'cracked', 'dropped', 'drowned', 'fallen', 'forgotten', 'frozen', 'full', 'half', 'quarter', 'rusted', 'soaked', 'spun', 'stabbed', 'tall', 'thirsty'] }; function randomWord(type) { var rando = Math.floor(Math.random() * words[type].length), word = words[type][rando]; return word; } function tavernName() { var W = randomWord('W'), W2 = randomWord('W'), X = randomWord('X'), Y = randomWord('Y'), Y2 = randomWord('Y'), Z = randomWord('Z'); var names = ['The ' + W + ' & ' + W2 + ' ', 'The ' + X + ' ' + W + ' ', 'The ' + W + "'s " + Y + ' ', 'The ' + Z + ' ' + W + ' ', 'The ' + Y + ' & ' + Y2 + ' ', 'The ' + W + " & " + Y + ' ', 'The ' + Z + ' ' + Y + ' ', 'The ' + X + ' ' + Y + ' ']; var name = names[Math.floor(Math.random() * names.length)]; var container = document.getElementById('output'); container.innerHTML = name; } $(function(){ tavernName(); $('.button').click(function(){ tavernName(); }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <div style="width: 100%; text-align: center;"> <h2 style="font-size: 48pt; font-family: Fredericka the Great;" id="output" class="button">&nbsp;</h2> </div> 

The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ).ready() method will run once the page DOM is ready to execute JavaScript code.

$( document ).ready(function() {
    console.log( "ready!" );
});

Experienced developers sometimes use the shorthand $() for $( document ).ready() .

$(function() {
    console.log( "ready!" );
});

For your problem you can add $('.button').click() method inside $(document).ready() like below,

// option 1
$(document).ready(function(){
   $('.button').click(function(){});
});

// option 2
$(function(){
   $('.button').click(function(){});
});

Other than that if you want to reuse this button click method you can create function() and call it whenever you need it.

function generateName() {
   var W = randomWord('W'),
   W2 = randomWord('W'),
   X = randomWord('X');
   ....
}

$(function(){
   $('.button').click(function(){
      generateName();
   });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM