javascript - jQuery 热键只工作一次

标签 javascript jquery

我有 4 个 radio 输入。

我已经为他们分配了热键。 (热键是 1、2、3 和 4)

这是我的 html 代码:

<label>
 <input type="radio" value="2" id="1" name="1">[c2]
</label>
<label>
 <input type="radio" value="4" id="2" name="1">[c4]
</label>
<label>
 <input type="radio" value="1" id="3" name="1">[c1]
</label>
<label>
 <input type="radio" value="3" id="4" name="1">[c3]
</label>

javascript代码:

$(document).keypress(function(e) {

  if(e.charCode == 49) {
    console.log("1");
    $('input:radio[id=1]').attr('checked',true);
  }

  if(e.charCode == 50) {
    console.log("2");
    $('input:radio[id=2]').attr('checked',true);
  }

  if(e.charCode == 51) {
    console.log("3");
    $('input:radio[id=3]').attr('checked',true);
  }

  if(e.charCode == 52) {
    console.log("4");
    $('input:radio[id=4]').attr('checked',true);
  }                  
});

你也可以看到,我把console.log事件写到脚本里只是为了观察。

对我来说奇怪的是,我只能通过热键为每个单选按钮选择一次 redio 按钮。

*

如果我按 1,它会选择正确的复选框并为我提供正确的控制台日志。

然后按2,效果一样。

但是如果我再次按 1,它会给我控制台日志,但热键不起作用。

这是 jsfiddle: https://jsfiddle.net/f07evno0/

如何让热键在一个 session 中多次使用?

最佳答案

你可能不得不使用

$("input:radio[id=2]").prop("checked", true)

$(document).keypress(function (e) {

        if (e.charCode == 49) {
            console.log("1");
            $('input:radio[id=1]').prop('checked', true);
        }

        if (e.charCode == 50) {
            console.log("2");
            $('input:radio[id=2]').prop('checked', true);
        }

        if (e.charCode == 51) {
            console.log("3");
            $('input:radio[id=3]').prop('checked', true);
        }

        if (e.charCode == 52) {
            console.log("4");
            $('input:radio[id=4]').prop('checked', true);
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<label>
    <input type="radio" value="2" id="1" name="1">[c2]
</label>
<label>
    <input type="radio" value="4" id="2" name="1">[c4]
</label>
<label>
    <input type="radio" value="1" id="3" name="1">[c1]
</label>
<label>
    <input type="radio" value="3" id="4" name="1">[c3]
</label>

试试https://jsfiddle.net/f07evno0/1/

关于javascript - jQuery 热键只工作一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39193249/

相关文章:

javascript - 如何取消挂起的 Jquery Ajax 调用?

jquery - 如何在鼠标未悬停时保持悬停,Jquery

javascript - 如何使用 Jquery 更改基于多个选择框的总和?

javascript - Angular JS,异步回调中的范围更新

javascript - 谷歌浏览器扩展用户脚本图标

javascript - 如何在 Vue 2.5 中从带有 html 标签的字符串创建 VNode?

javascript - 单击菜单更改文本

php - jquery日历从mysql数据库中拉取信息

javascript - JavaScript 中的减法仅返回千位中的两位数

javascript - 如何在 Javascript 中将 slider 绑定(bind)到变量?