包括jQuery会导致标准JavaScript停止运行? [英] Including jQuery causes standard JavaScript to stop functioning?
问题描述
我正在开始使用jQuery.我一直在尝试将其与我现有的一些JavaScript代码混合使用,因此不必重写所有内容.我读过很多地方,这完全可行.但是,每当我包含jQuery的任何行时,标准的JavaScript就会停止运行.
I'm getting started with jQuery. I'v been trying to mix it with some of my preexisting JavaScript code so I don't have to rewrite everything. I have read many places that this is totally doable. However, whenever i include any lines of jQuery the standard JavaScript stops functioning.
以下是一些示例:
<!DOCTYPE html>
<html>
<head>
<style>
#testjquery {
height: 300px;
width: 300px;
}
</style>
</head>
<body>
<div id="testjquery" onclick="testClick()">This is the stuff.</div>
<script src='jquery-1.10.2.min.js'></script>
<script>
$(document).ready(function() {
function testClick() {
document.getElementById("testjquery").style.background = "blue";
}
});
</script>
</body>
</html>
这不起作用,并且当我单击时,我得到一个函数未定义的错误.
This doesn't work, and when clicks I get a function not defined error.
但是,把它放在体内
<body>
<div id="testjquery">This is the stuff.</div>
<script src='jquery-1.10.2.min.js'></script>
<script>
$(document).ready(function() {
$("#testjquery").click(function() {
$(this).css("background", "blue");
});
});
</script>
</body>
工作正常,标准JavaScript中的等效功能也是如此.
Works fine, as does the equivalent in standard JavaScript.
推荐答案
请勿将函数包装在DOM ready($(document).ready(function(){)
处理程序中.由于它是匿名函数,因此您的testClick()
函数具有local scope
.在DOM ready
Don't wrap your function in DOM ready($(document).ready(function(){)
handler.As it is a anonymous function so your testClick()
function has local scope
.So you can not call it outside the DOM ready
function testClick() {
document.getElementById("testjquery").style.background = "blue";
}
这篇关于包括jQuery会导致标准JavaScript停止运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!