简体   繁体   中英

calling the selected loop element in a method in a .onclick function

I tried to call the method addProject() with the the second argument as current selected element in the loop. But the reference of the argument is null , when I called addProject() .

I think the reference of the current selected argument in the loop is lost when I'm using the .onclick button. But how can I give this argument to the method in a different way?

$(document).ready(function () {
    for (var i = 0; i <= proj_array.length - 1; i++) {
        var h = document.createElement("h1");
        var p = document.createElement("p");
        p.innerHTML = proj_array[i].projectdescription;
        h.innerHTML = proj_array[i].projectname;

        $(".projectsList").append(h).append(p);

        var button = document.createElement("button");
        button.style.width = "70px";
        button.style.height = "27px";
        button.innerHTML = "Add";

        $(button).addClass("enable");
        button.onclick = function () {
            if ($(button).hasClass("enable")) {
                addProject(this, proj_array[i]);
            }
        }
        $(p).append(button);
    }
    $(".projectsList").accordion();
});

You need a closure:

(function(proj) {
    $(button).on('click', function() {
        if ( $(this).hasClass("enable") ) {
            addProject(this, proj);     
        }
    });
})(proj_array[i]);

Or you could just stick with jQuery and not complicate this too much:

$(function() {
    $.each(proj_array, function(i, proj) {
        var h = $('<h1 />', {html: proj.projectdescription}),
            p = $('<p />', {html: proj.projectname}),
            button = $('<button />', {
                                      width  : '70px',
                                      height : '27px',
                                      html   : 'Add',
                                      'class':'enable'
                                     });

        button.on('click', function() {
            if ($(this).hasClass("enable")) {
                addProject(this, proj);     
            }
        });
        $(p).append(button);
        $(".projectsList").append(h, p).accordion();
    });
});

Store it as a data-* attribute:

var button = document.createElement("button");
$(button).data('proj', proj_array[i]);

In the onclick you can retrieve it:

if($(this).hasClass("enable")) {
    addProject(this, $(this).data('proj'));
}

Also use $(this) not $(button) in the click handler.

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