2

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.

Here's a few examples:

<!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.

But, putting this in the body

<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>

Works fine, as does the equivalent in standard JavaScript.

4

2 回答 2

9

不要将你的函数包装在处理程序中。DOM ready($(document).ready(function(){)因为它是一个匿名函数,所以你的testClick()函数有local scope。所以你不能在外面调用它DOM ready

function testClick() {
    document.getElementById("testjquery").style.background = "blue";
}

阅读JavaScript 中变量的范围是什么?

于 2013-11-10T16:44:11.903 回答
5

下面的代码块在文档准备就绪时运行,并创建一个在匿名函数之外不可见的本地函数(由第一行创建的函数)。testClick()function(){

$(document).ready(function(){ 
function testClick(){
document.getElementById("testjquery").style.background="blue";
}
});

如果要定义可以直接调用的全局函数,则不应将其放在文档就绪处理程序中。改为此。

function testClick(){
  document.getElementById("testjquery").style.background="blue";
}
于 2013-11-10T16:46:23.787 回答