我有这个外部 jQuery 代码:
jQuery(document).one('keydown', 'g',function (evt){
if ($("#tb").html() == "0")
{
$("#tb").html("Testing the chicken.")
} else {$("#tb").html("Chickens fart too.")}
return false;});
控制台没有错误。
我知道这很愚蠢,但不要介意 .html() 中的文本。无论如何,每当我访问该网页时,它只是将页面中的默认值 0 替换为空。然后,当我按任意键时,什么也没有发生。最后,我希望这个脚本最终做的是显示用户在 tb
div 中键入的字母或数字。
附言我是 stackoverflow 的新手,所以如果我的格式有误或者我违反了规则,请告诉我。
好的,所以我编辑了代码,这就是我所拥有的:
$('#tb').on("keydown", function(event) {
if ($("#tb").html() == "0")
{
$("#tb").html("Testing the chicken.")
} else {$("#tb").html("Chickens fart too.")}
});
还是不行。
最佳答案
div 元素没有keydown 事件
。只有具有 focus 属性的元素才能拥有它。
所以我认为你指的是 div 中的输入..
HTML
<div id="tb">
<span class="output"></span>
<input type="text" />
</div>
JS
// Delegating the event on input to it's container
$('#tb').on("keydown", 'input', function (event) {
// $(this).val() - Gets the value of the input on keydown
if ($(this).val() === "") {
// Set the html for span inside div
$(".output").html("Testing the chicken.");
} else {
$(".output").html("Chickens fart too.");
}
});
// Bind event to the document which fires when document is focussed and
// a key is pressed
$(document).on('keydown', function(event) {
// Key code for g
if(event.keyCode === 71) {
// Bind the event to the input when g is pressed
$('#tb input').on('keyup', inputKeydown);
// unbind the event on document as no longet necessary
$(document).off('keydown');
}
return;
});
function inputKeydown() {
// $(this).val() - Gets the value of the input on keydown
if ($(this).val() === "") {
// Set the html for span inside div
$(".output").html("Testing the chicken.");
} else {
$(".output").html("Chickens fart too.");
}
}
关于javascript - 为什么 jQuery 在 keydown 时不能正常运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17245988/