为什么这个 jQuery 运行 - 但在我的页面上不起作用 - 尽管它在 jsfiddle 中有效?

Why is this jQuery running -- but not working -- on my page, although it works in jsfiddle?

我想将文本元素中的条目限制为仅限数字。我找到了一些适用于 the jsfiddle, which is referenced from here

的代码

...但在我的页面 (Webpart) / *.ascx 文件中,它没有。每次按下键时我都会看到警报,但我可以输入任何内容(a..z 以及 0..9)。这是代码:

<script type="text/javascript">
$(document).ready(function () {
    console.log('The ready function has been reached'); /* This is a "sanity check" so it can be verified that this jQuery script is running/ran */
});

/* When "Employee" checkbox changes state, set up txtbxSSNOrITIN accordingly */
$(document).on("change", '[id$=ckbxEmp]', function () {
    var ssnmaxlen = 4;
    var itinmaxlen = 11;
    var ssntextboxwidth = 40;
    var itintextboxwidth = 100;
    var ckd = this.checked;
    var $input = $('[id$=txtbxSSNOrITIN]');
    var $lbl = $('[id$=lblSSNOrITIN]');

    if (ckd) $input.data("oldValue", $input.val()); // Remember current value

    $input.prop("maxlength", ckd ? ssnmaxlen : itinmaxlen).css({
        background: ckd ? 'yellow' : 'lightgreen',
        width: ckd ? ssntextboxwidth : itintextboxwidth
    }).val(function (i, v) {
        /* If checked, trim textbox contents to ssnmaxlen characters */
        return ckd && v.length > ssnmaxlen ? v.slice(0, ssnmaxlen) : $input.data("oldValue");
    });

    $lbl.text(ckd ? "SSN - last 4 digits" : "ITIN");
    /* This sets focus to the end of the textbox (multiplication by 2 is because some characters are counted as two) */
    var strLength = $input.val().length * 2;
    $input.focus();
    $input[0].setSelectionRange(strLength, strLength);
});

$(document).on("keyup", '[id$=txtbxSSNOrITIN]', function (e) {
    alert('the textbox keyup event occurred');
    /* For now, just "eating" non-numeric entries (from http://jsfiddle.net/zpg8k/); will change when the business rules for ITIN are known */
    var a = [];
    var k = e.which;

    for (i = 48; i < 58; i++)
        a.push(i);

    if (!(a.indexOf(k) >= 0))
        e.preventDefault();
});
</script>

无论 "keyup" 事件是 "standalone" 还是在 ready 函数内,它的工作原理都是一样的 - 在这两种情况下,每次按下键都会显示警报,但不限制任何内容。为什么?

更新

感谢 putvande 和 Brett(以及 Roko,在其他地方提供 "soul-saving" ID 查找技巧),它现在可以使用,并已简化为:

$(document).on("keypress", '[id$=txtbxSSNOrITIN]', function (e) { 
    var k = e.which;
    if (k < 48 || k > 57) { e.preventDefault(); }
});

这是因为您的函数在您按下该键后运行。这样一来,它就不会阻止您按下并输入该键。你引用的 JSFiddle 以前做过。
因此,将您的功能更改为:

$(document).on("keypress", '[id$=txtbxSSNOrITIN]', function (e) {
//              ^^^^^^^^keypress instead of keyup
    alert('the textbox keyup event occurred');
    /* For now, just "eating" non-numeric entries (from http://jsfiddle.net/zpg8k/); will change when the business rules for ITIN are known */
    var a = [];
    var k = e.which;

    for (i = 48; i < 58; i++)
    a.push(i);

    if (!(a.indexOf(k) >= 0)) e.preventDefault();
});