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