jQuery正在加载,但是,我得到一个“$未定义”错误

时间:2017-05-15 20:37:13

标签: javascript jquery html

所以,我为一项任务编写游戏,我一直在努力实现击键。在大多数情况下,我已设法这样做,虽然有时我得到这个错误,即使我正确加载jquery(我认为)。 想知道这里可能出现什么问题吗?

<svg width=1300 height=900>

<image x=0 y=0 width=670 height=900 xlink:href=http://localhost/images/firstscreen.png />
<a id="single" xlink:href=http://localhost/cgi-bin/jogo?g>
<image x=200 y=400 width=400 height=150 xlink:href=http://localhost/images/start_button.png />
</a>
<a id="double" xlink:href=http://localhost/cgi-bin/jogo?h>
<image x=200 y=600 width=400 height=150 xlink:href=http://localhost/images/hscores.png />
</a>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<script>
	 	$(document).keydown(function(e){
	 		if(e.keyCode == 13) {
		 			e.preventDefault();
			 			window.location.href = document.getElementById('single').href.animVal;
		 		}
	 		if(e.keyCode == 8) {
		 			e.preventDefault();
			 			window.location.href = document.getElementById('double').href.animVal;
		 		}
	 	});
</script>
</svg>

2 个答案:

答案 0 :(得分:0)

在尝试使用jQuery之前,可能没有在DOM上加载jQuery。你可以试试这段代码:

document.addEventListener("DOMContentLoaded", function(event) { 
    $(document).keydown(function(e){
         if(e.keyCode == 13) {
            e.preventDefault();
            window.location.href = document.getElementById('single').href.animVal;
         }
         if(e.keyCode == 8) {
             e.preventDefault();
             window.location.href = document.getElementById('double').href.animVal;
         }
    });
}); 

答案 1 :(得分:0)

问题是你在SVG标签中包含了jQuery库,

所以SVG代码标签之外的jQuery库:

试试这个:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<svg width=1300 height=900>

<image x=0 y=0 width=670 height=900 xlink:href=http://localhost/images/firstscreen.png />
<a id="single" xlink:href=http://localhost/cgi-bin/jogo?g>
<image x=200 y=400 width=400 height=150 xlink:href=http://localhost/images/start_button.png />
</a>
<a id="double" xlink:href=http://localhost/cgi-bin/jogo?h>
<image x=200 y=600 width=400 height=150 xlink:href=http://localhost/images/hscores.png />
</a>
<script>
	 	$(document).keydown(function(e){
	 		if(e.keyCode == 13) {
		 			e.preventDefault();
			 			window.location.href = document.getElementById('single').href.animVal;
		 		}
	 		if(e.keyCode == 8) {
		 			e.preventDefault();
			 			window.location.href = document.getElementById('double').href.animVal;
		 		}
	 	});
</script>
</svg>