简体   繁体   中英

Adding jQuery click event within loop “auto” clicks all events

I've got a jQuery fucntion that performs a simple Ajax GET in ASP.Net and with the data (Json array) it gets back, populates a web page.

I'm attempting to bind a click event to each div created with the lopp below, but when this is run, all the click events happen on page load simultaneously!

Any ideas?

function grabList() {
    $('#temp').empty();

    $.ajax({
        url: '/Home/GoModel',
        method: 'GET',
        success: function (data) {             
            for (var i = 0; i < data.length; i++) {
                $('#temp').append('<div class="host col-sm-3"> id=' + data[i].name + '>' + data[i].name + '</div>');

                if (data[i].hostConnected === true) {
                    $('#temp').append('<div class="host connected col-sm-3" id=' + data[i].name + '>' + data[i].name + '</div>');
                    continue;
                }

                $('#' + data[i].name).on('click', connect(data[i].name)); // Problem occurs
            }
            $('#container').html($('#temp').html());
        }
    });
}

You may try:

 function grabList() { $('#temp').empty(); $.ajax({ url: 'https://api.github.com/repositories?since=700', method: 'GET', success: function (data) { for (var i = 0; i < data.length; i++) { $('#temp').append('<div class="host col-sm-3" id=' + data[i].name + '>' + data[i].name + '</div>'); if (data[i].hostConnected === true) { $('#temp').append('<div class="host connected col-sm-3" id=' + data[i].name + '>' + data[i].name + '</div>'); continue; } (function (ele) { $('#' + ele).on('click', function (e) { alert(ele); }); })(data[i].name); } $('#container').html($('#temp').html()); } }); } $(function () { grabList(); }); 
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://code.jquery.com/jquery-1.12.1.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <div id="temp"></div> <div id="container"></div> 

It is not firing the event, you are making a call in the binding :

$('#' + data[i].name).on('click', connect(data[i].name)); 

You need to do it like this :

$('#' + data[i].name).data({name : data[i].name});
    $('#' + data[i].name).on('click', function(e){connect($(e.target).data().name);}); 

You are, in fact, calling the connect() function when binding to the click event instead of when the event is fired (later).

Since you want to pass data into the event handler, you'll need to use additional parameters of the .on() call. Try something like this instead.

$('#' + data[i].name).on('click', null, data[i].name, function (e) {
    connect(e.data);
});

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