如何使用这个JavaScript

时间:2013-08-27 10:45:08

标签: javascript jquery html css

目前我遇到了一个实现Javascript的问题。这是链接

http://jsfiddle.net/joplomacedo/WzA4y/

这是有用的我正在使用Microsoft Visual Studio 2010并且我有小文件一个是html,另一个是CSS,我使用Javscript,如下面的代码,但这不像jsFiddle上面链接那样工作。

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>

 <script type="text/jscript" language="javascript">
    var body = $('body'),
    main = $('.main'),
    open_modal = $('.open-modal'),
    close_modal = $('.close-modal'),
    modal_container = $('.modal-container'),
    toggleModal = function() {
        body.toggleClass('body-locked');
        modal_container.toggleClass('dp-block');
    };

    open_modal.on('click', toggleModal);
    close_modal.on('click', toggleModal);

 </script>


</head>

<body>

<button class="open-modal">Button!</button>


<div class="modal-container dp-none">
    <div class="modal">
        <button class="close-modal">Close!</button>

    </div>
</div>

</body>
</html>

2 个答案:

答案 0 :(得分:3)

您需要将javascript / jquery代码包装到$(document).ready(function(){})中;因为否则你试图在加载之前访问DOM元素。

如果你在你提供的jsFiddle链接中注意到,你正在使用jQuery 1.7.2并加载代码'onload',所以jsFiddle正在为你做这个。

 $(document).ready(function(){
    var body = $('body'),
    main = $('.main'),
    open_modal = $('.open-modal'),
    close_modal = $('.close-modal'),
    modal_container = $('.modal-container'),
    toggleModal = function() {
        body.toggleClass('body-locked');
        modal_container.toggleClass('dp-block');
    };

    open_modal.on('click', toggleModal);
    close_modal.on('click', toggleModal);
 });

答案 1 :(得分:1)

将您的jquery代码包装在

$(function(){
      /* your code here */
});

这样的事情:(我在你的代码中做了一些小改动,使我的答案有点大

$(function () {
    var body = $('body'),
        main = $('.main'),
        modals = $('.open-modal, .close-modal'),
        modal_container = $('.modal-container'),
        toggleModal = function () {
            body.toggleClass('body-locked');
            modal_container.toggleClass('dp-block');
        };

    modals.on('click', toggleModal);
});