href 点击未在 jquery 中触发

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>

请帮忙?

如果您使用事件委托,您的问题就会消失(并且您的应用程序会变得更高效并且更不容易发生内存泄漏)。

// 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);
});

由于您的 .move 元素是动态添加到页面的,因此您必须使用 jQuery's on() method 将事件 委托 .move 元素在您的 JavaScript 首次加载时确实存在。

$(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.

您可以阅读更多关于 jQuery 的事件委托 here

试试这个

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

事件未被触发的原因是,当您调用 .click() 方法时,事件仅添加到页面上存在的元素。

相反,您可以使用事件委托:

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

这实际上是说:当单击 document.body 中与 .move 匹配的任何元素时调用该函数。

我知道其他人已经说过了,但我想让事件委托更清楚。