简体   繁体   English

为什么返回document.getElementById不起作用

[英]why return document.getElementById doesn't work

var $ = function (id){return document.getElementById(id);}
 window.onload=function(){
 $("num").onfocus=function(){
        $("show").style.display="block";
 }

Uncaught TypeError: undefined is not a function 未捕获的TypeError:undefined不是函数

but when i change $("num") to $("#num") it can works ,why? 但是当我将$(“ num”)更改为$(“#num”)时,为什么可以呢?

You must have jQuery loaded on your page, and you define $ as a local variable, so during the onload the $ variable take it's old signification which is jQuery. 您必须在页面上加载jQuery,并且将$定义为局部变量,因此在onload期间,$变量采用旧的含义,即jQuery。 And jQuery uses the same selectors as CSS. jQuery使用与CSS相同的选择器。

You can solve your problem by disabling jQuery if you don't need it, or setting it in compatibility mode, or setting your $ variable as global variable. 您可以通过禁用不需要的jQuery或将其设置为兼容模式或将$变量设置为全局变量来解决问题。

Your code works if you 如果您的代码有效

a) do not have jQuery loaded a)没有加载jQuery

b) add the missing curly bracket b)添加缺少的花括号

Live demo 现场演示

var $ = function (id){return document.getElementById(id);} 

window.onload=function(){
   $("num").onfocus=function(){
        $("show").style.display="block";
   }       
 }

You're most probably referencing uninformative jQuery $ variable name. 您最有可能引用的是信息量不大的 jQuery $变量名。 And the reason is that both window.jQuery and window.$ are pointing to jQuery instance in case of referencing jQuery framework (sources) . 原因是在引用jQuery框架(源)的情况下, window.jQuerywindow.$都指向jQuery实例。


In fact, next should work as expected: 实际上,next应该能按预期工作:

  window.onload=function(){ var $ = function (id){return document.getElementById(id);} $("num").onfocus=function(){ $("show").style.display="block"; } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM