jquery - Bootstrap 按钮按键不适用于 'Enter' 键

标签 jquery html twitter-bootstrap keypress enter

所以我正在构建一个网站,当按下按钮时,该网站会随机打印数组中的引号。当人们用鼠标按下按钮时,它现在正在工作。但是,我添加了代码来监听“Enter”键以单击所述按钮,但它不起作用。今天我已经用我的代码玩了一段时间了,但我仍然无法让它工作。这是我现在的代码:

JQuery:

$(document).ready(function(){
 var quotes = ['"A dream does not become reality through magic; it takes sweat, determination, and hard work." - Colin Powell', 
'"Success is the result of perfection, hard work, learning from failure, loyalty, and persistence." - Colin Powell', 
'"Nothing ever comes to one, that is worth having, except as a result of hard work." - Booker T. Washington', 
'"I learned the value of hard work by working hard" - Margaret Mead', 
'"Out work everyone. If you are working harder than everybody, then what are you worrying about?" - John Sonmez', 
'"Those dreams that you have, those goals that you have, do not put them off another second. Get on them. Go out and make them happen starting right now" - Jocko Willink', 
'"Go to bed tired." - Tim Kennedy', 
'"Do that thing that you dont know if you can do. Stop being afraid of hard work." - Tim Kennedy', 
'"Discipline equals freedom. The more discipline you have, the harder you work, the more effort you put into it, the more freedom you are going to have." - Jocko Willink',
'"Dont think about it, start doing it." - Anonymous'];

var rand = quotes[Math.floor( Math.random() * quotes.length )];
 $('blockquote').text(rand); 

//On Button Click 
$('#newQuote').click(function(){
  $('blockquote').text(quotes[Math.floor(Math.random() * quotes.length)]);
});

//Listen for Enter Key
$('blockquote').keyup(function(event){
if(event.keyCode == 13){
    $('#newQuote').click();
    $('blockquote').text(quotes[Math.floor(Math.random() * quotes.length)]);
 }

  });
});

还有我的 HTML:

<a id ="newQuote" class="btn btn-primary btn-lg">New Quote</a>

这里还有 codepen 上的网站:http://codepen.io/codyreandeau/pen/VmzWXG

最佳答案

我认为你需要更改你的 keydown 监听器 进入此


    $('#newQuote').keyup(function(event){
    if(event.keyCode == 13){
        $('blockquote').text(quotes[Math.floor( Math.random() * quotes.length )]);
    }
    });

and your button into this

<button id="newQuote" class="btn btn-primary btn-lg">New Quote</button>

关于jquery - Bootstrap 按钮按键不适用于 'Enter' 键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40955535/

相关文章:

javascript - 如何将 html 标题(工具提示)添加到 leaflet.js 多边形?

javascript - 页面加载时,@Url.Action 为 null 或 javascript 中的 ""

html - Angular 5 如何等待 styles.css 加载

html - 如何使用 &nbsp 字符进行换行?

javascript - 过滤数据后打开模态 Bootstrap

html - 单击和悬停在下拉菜单上时更改下拉菜单的颜色

javascript - 按另一个 <a> 按钮后从 <a> 按钮中删除类

jquery - 获取 JQuery JStree 中选中的元素

javascript - 滚动到正确位置时,将导航栏保持在页面顶部

javascript 多语言元描述