Uncaught TypeError: Cannot read properties of undefined (reading 'preventDefault')

Uncaught TypeError: Cannot read properties of undefined (reading 'preventDefault')

我根据特定进程在输入中触发 onchange 属性。但是,即使我将“事件”作为参数,我仍然会收到以下错误。另外,或者,我尝试了 Event.StopPropagation () 和 Return False 但问题仍在继续。

$(function () {
        test();
});

function test(obj) {

        var inputValue = parseInt($(obj).val());

        if (($(obj).val() < 0 || $(obj).val() > 100) && event.keyCode !== 46 // keycode for delete
            && event.keyCode !== 8 // keycode for backspace
        ) {
            event.preventDefault();
            $(obj).val(0);
        } else if (isNaN(inputValue)) {
            event.preventDefault();
            $(obj).val(0);
        }
}
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>

<div>
<input id="weightInput" type="number" class="form-control weightInput"  data-key="" data-guid="" onchange="test(this)" value="" />
</div>

您需要将 event 作为显式参数传递给 onchange 参数。

您也不应该从 $(function() { }) 调用它,因为那里没有事件。

function test(obj, event) {
  var inputValue = parseInt($(obj).val());
  if (($(obj).val() < 0 || $(obj).val() > 100) && event.keyCode !== 46 // keycode for delete
    &&
    event.keyCode !== 8 // keycode for backspace
  ) {
    event.preventDefault();
    $(obj).val(0);
  } else if (isNaN(inputValue)) {
    event.preventDefault();
    $(obj).val(0);
  }
}
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>

<div>
  <input id="weightInput" type="number" class="form-control weightInput" data-key="" data-guid="" onchange="test(this, event)" value="" />
</div>

您应该使用 jQuery 的侦听器来处理当前代码中未定义的事件。您还应该使用事件目标作为对象

/***This here**/
jQuery(document).on('change','#weightInput',test);
function test(event) {
        let obj = event.target
        var inputValue = parseInt($(obj).val());

        if (($(obj).val() < 0 || $(obj).val() > 100) && event.keyCode !== 46 // keycode for delete
            && event.keyCode !== 8 // keycode for backspace
        ) {
            event.preventDefault();
            $(obj).val(0);
        } else if (isNaN(inputValue)) {
            event.preventDefault();
            $(obj).val(0);
        }
}