Javascript参考错误

问题描述 投票:0回答:1

我正在尝试在keydown上调用javascript函数,但是我有一个错误:

/* Calling the javascript file */
$(document).ready(function() {
		item_set();
});

/* custom.js */
function item_set(){
	$(document).ready(function() {
  function check(idname) {	
          // Allow: backspace, delete, tab, escape, enter and .
      var e=document.getElementById(idname);
          if (jQuery.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
               // Allow: Ctrl+A, Command+A
              (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) || 
               // Allow: home, end, left, right, down, up
              (e.keyCode >= 35 && e.keyCode <= 40)) {
                   // let it happen, don't do anything
                   return;
          }
          // Ensure that it is a number and stop the keypress
          if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
              e.preventDefault();
          }
      };
   };
<input type="text" name="item_cost" id="item_cost" class="form-control" onkeydown="check(item_cost)" />

控制台中的错误是:

ReferenceError:未定义检查

这有什么问题?

javascript php jquery
1个回答
0
投票

我认为您的问题是您需要在调用文件中引用自定义脚本。

<script src="custom.js"></script>
<script>
  $(document).ready(function() {
    item_set(); //now you have access to this function
  });
</script>

旁注:我喜欢将所有脚本放在<body>的末尾,这样你就不必费心去用$(document).ready()

...
<body>
  ...
  html
  and
  stuff
  ...
  <script src="custom.js"></script>
  <script>
    item_set();
  </script>
</body>
© www.soinside.com 2019 - 2024. All rights reserved.