简体   繁体   中英

Jquery .on event not firing in chrome

I am trying to reproduce some thing that works on codecademy: https://www.codecademy.com/en/courses/web-beginner-en-v6phg/2/5?curriculum_id=50a3fad8c7a770b5fd0007a1

However, when I copied down the html, css, and js files and ran it with google chrome, nothing was working. I noticed the missing <script> link to Jquery and added it, and fixed the 'add' function; however the 'remove part' never worked.

Ps. I made sure the script is correctly linked by adding an alert , which fired.

Here is the html:

<!DOCTYPE html>
<html>
    <head>
        <title>To Do</title>
        <link rel="stylesheet" type="text/css" href="stylesheet.css"/>
        <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js?ver=1.4.2'></script>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
        <h2>Checklist</h2>
        <form name="checkListForm">
            <input type="text" name="checkListItem"/>
        </form>
        <div id="button">Add!</div>
        <br/>
        <div class="list"></div>
    </body>
</html>

and jquery (js) file:

$(document).ready(function() {
    $('#button').click(function() {
        var toAdd = $('input[name=checkListItem]').val();
        $('.list').append('<div class="item">' + toAdd + '</div>');
        $('input[name=checkListItem]').val('');
    });
    $(document.body).on('click', '.item', function(event) {
        $(this).remove();
    });
});

I just found out the issue to be using old version of jQuery. You are using 1.4.2 , which doesn't have the .on() function.

<script type='text/javascript' 
        src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js?ver=1.4.2'></script>
<!-------------------------------------------------------^^^^^

Solution: Use the latest version of jQuery 1.x, which is 1.12 .

From the manual:

手册

I would really suggest you to check the console first before posting something here.

If you sticky with old library then use .live() instead of .on(). Hope this will work for you.

$(document).ready(function() {
    $('#button').click(function() {
        var toAdd = $('input[name=checkListItem]').val();
        $('.list').append('<div class="item">' + toAdd + '</div>');
        $('input[name=checkListItem]').val('');
    });
    $(".item").live('click', function() {
        $(this).remove();
    });
});

Demo: https://jsfiddle.net/8s19ehh8/5/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM