javascript - 为什么 jQuery 在 keydown 时不能正常运行?

标签 javascript jquery html css

我有这个外部 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.");
    }
});

Check Fiddle

// 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.");
    }
}

Another Fiddle

关于javascript - 为什么 jQuery 在 keydown 时不能正常运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17245988/

相关文章:

javascript - 在可变高度图像的特定区域上定位 div

javascript - dc.js 饼图在 filterAll() 之后没有更新

javascript - 使用 jQuery 显示没有特定类的元素的第一个子元素

jquery - CSS 和 jQuery 简单问题

javascript - 在materializecss中,如何从右侧而不是默认左侧打开滑出菜单?

javascript - 带有动态 div 的 JQuery 对话框

javascript - 指定括号内的参数和不指定括号内的参数有什么区别?

javascript - 继承nodejs

jquery - IE7 JQuery、Ajax 和 CSS 的问题

javascript - jquery onload/text effect 后期 react