【问题标题】:Is it possible to combine document.ready function and a button click function?是否可以结合 document.ready 功能和按钮单击功能?
【发布时间】:2019-08-28 21:59:56
【问题描述】:

我正在尝试编写一个随机的酒馆名称生成器,并希望在加载文档时准备好名称,并单击按钮以生成新名称。

我想知道我是否能够结合这个 document.ready 功能:

    $(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;

它们是相同的功能,但有两个不同的触发器。

我可以做类似...的事情吗?

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

谢谢!

(出于测试目的,整个代码为: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>

【问题讨论】:

    标签: javascript jquery button document-ready


    【解决方案1】:

    我建议将您的代码放入一个函数中,因为您需要多次使用它。第一个实例在页面加载时运行,然后您可以将第二个实例绑定到点击事件。

    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>

    【讨论】:

    • 完美!非常感谢!
    【解决方案2】:

    ready() 方法用于在加载文档后使函数可用。一旦页面 DOM 准备好执行 JavaScript 代码,您在 $(document ).ready() 方法中编写的任何代码都会运行。

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

    经验丰富的开发人员有时会使用简写 $() 来表示 $( document ).ready()。

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

    对于您的问题,您可以在$(document).ready() 中添加$('.button').click() 方法,如下所示,

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

    除此之外,如果您想重复使用此按钮单击方法,您可以创建function() 并在需要时调用它。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-15
      • 1970-01-01
      • 2011-01-26
      • 2013-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多