JavaScript在JSFiddle中工作,但不是单独使用

时间:2013-10-04 14:04:38

标签: javascript jquery ajax html5 css3

我不知道这段代码中发生了什么:/。代码是对的,我甚至也附加了jQuery库文件,但它仍然无法正常工作。我想为选定的li申请一个班级而不是其他班级。

<html>
    <head>
        <script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'></script>
        <style type="text/css">
            a.active {
                background-color:yellow;
            }
        </style>
        <script>
             $('li a').click(function(e) {
                    e.preventDefault();
                    $('a').removeClass('active');
                    $(this).addClass('active');
              });
        </script>
    </head>
    <body>
        <ul>
            <li><a href="#1">Photography</a></li>
            <li><a href="#2">Web</a></li>
            <li><a href="#3">Print</a></li>
        </ul>
    </body>
</html>

http://jsfiddle.net/rq9UB/

3 个答案:

答案 0 :(得分:1)

更改为:

<script>
$(document).ready(function(){
    $('li a').click(function (e) {
        e.preventDefault();
        $('a').removeClass('active');
        $(this).addClass('active');
    });
});
</script>

我添加了一个ready()函数:一个在DOM完全加载时执行的函数。

当jQuery正在寻找附加点击处理程序的那些元素时,它们还没有加载,所以$('li a')是空的。

另一种方法是在关闭body标签之前放置脚本。

答案 1 :(得分:1)

正确使用ready()

$(document).ready(function()
{
    $('li a').click(function(e)
    {
        $('a').removeClass('active');
        $(this).addClass('active');
        e.preventDefault();
    })
})


jsFiddle

答案 2 :(得分:0)

尝试以下,区别在于不等待dom准备就绪,因为你看到dom已经在脚本之前加载了。在页面末尾添加脚本也被认为是一种很好的做法。

<html>
<head>
    <script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'></script>
    <style type="text/css">
        a.active {
            background-color:yellow;
        }
    </style>
</head>
<body>
    <ul>
        <li><a href="#1">Photography</a></li>
        <li><a href="#2">Web</a></li>
        <li><a href="#3">Print</a></li>
    </ul>
    <script>
         $('li a').click(function(e) {
                e.preventDefault();
                $('a').removeClass('active');
                $(this).addClass('active');
          });
    </script>
</body>