简体   繁体   中英

a href click not triggering in jquery

        $(function() {

            $.getJSON("companies.json", function(response) {

                var html = '<table id="tbl">';
                response.businesses.forEach(function(row) {
                    html += '<tr><td><a href="#" class="move" idname="' + row.id + '">' + row.id + '</a></td><td>' + row.name;
                });
                html += '</table>';

                $("#tabledata").html(html);
            });


            $(".move").click(function() {

                var $id = $(this).attr("idname");

                $.getJSON("companies.json", function(response) {


                    $.map(response.businesses, function(obj) {
                        if (obj.id == $id)
                            console.log(obj);
                        return obj; // or return obj.name, whatever.
                    });
                });
            });
        });

HTML:

    <div id="tabledata" class='left'></div>
    <div class="right"></div>

Please help?

If you use event delegation, your problem goes away (and your app becomes more performant and less prone to memory leaks).

// Only do this once, when your page loads...
$(document.body).on('click', '.move', function (ev) {
    // This is the link that was clicked.
    var $targ = $(ev.target);
});

As your .move element is added to your page dynamically, you have to make use of jQuery's on() method to delegate the event to an ancestor of the .move element which does exist when your JavaScript first loads.

$(document).on('click', '.move', function() { ... });

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

You can read more about jQuery's event delegation here .

尝试这个

$('#tabledata').on('click', '.move', function(e) { ... });

The reason the event isn't being triggered is because the event is only added to elements that exist on the page when you call the .click() method.

Instead, you can use event delegation:

$(document.body).on('click', '.move', function (ev) {
    var $targ = $(ev.target);
}); 

which really says: call the function when any element that matches .move that's inside document.body is clicked.

I know others have said this already but I wanted to make event delegation clearer.

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