Javascript / jQuery onclick不工作 [英] Javascript/jQuery onclick not working

查看:98
本文介绍了Javascript / jQuery onclick不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个test.html文档来测试脚本。不知怎的,它不工作,我不能得到为什么没有发生。脚本在-tags中,用-tag包装,css也有-tags。为什么不工作?这是代码

i made a test.html document to test a script. Somehow it is not working and i can't get why nothing is happening. The Script is in -tags and wrapped with -tag and the css also has it´s -tags. Why shouldn't it work? Here is the code

<!DOCTYPE html>
<html>

    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
        </script>
        <script>
        $('#menu li a').on('click', function() {
            $('li a.current').removeClass('current');
            $(this).addClass('current');
        });
        </script>
        <style>
        .current {
            text-decoration: underline;
        }

        ul {
            list-style-type: none;
        }

        a {
            text-decoration: none;
        }
        </style>
    </head>

    <body>
        <div id="menu">
            <ul>
                <li><a id="about-link" class="current" href="#">ABOUT</a></li>
                <li><a id="events-link" href="#">EVENTS</a></li>
                <li><a id="reviews-link" href="#">REVIEWS</a></li>
                <li><a id="contact-link" href="#">CONTACT</a></li>
            </ul>
        </div>
    </body>

</html>


推荐答案

元素存在于 DOM 中,则事件不会绑定在元素上。

Because your code for binding event handler is executed before the elements is present in DOM, the event is not bound on the element.

为了解决这个问题,


  1. 将代码包含在 ready()回调中, c>完成加载

  2. 将脚本移动到< body> ,所以所有元素都存在于 DOM 中,并且您可以绑定它上的事件

  1. Wrap your code in ready() callback, so that your code will be executed when DOM is finished loading
  2. Move your script to the end of <body>, so all the elements are present in DOM and you can bind the events on it

代码:

$(document).ready(function () {
    $('#menu li a').on('click', function () {
        $('li a.current').removeClass('current');
        $(this).addClass('current');
    });
});

EDIT

您也可以使用加载不推荐)事件回调来绑定事件,但这将等待所有资源完全加载。

You can also use load(not recommended) event callback to bind the event, but this will wait for all the resources to load completely.

如果您想使用Vanilla Javascript,可以使用

If you want to use Vanilla Javascript, you can use DOMContentLoaded event on document.

这篇关于Javascript / jQuery onclick不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆