我正在尝试从您选择的框中获取名字和姓氏。问题在于,它只给我最后一个值,与选择哪个框无关。

for (var i = 0; i<obj.length; i++) {
    firstname = obj[i].Firstname;
    lastname = obj[i].Lastname;

    var checkbox = document.createElement('input');

    checkbox.type = "checkbox";
    checkbox.name = "name";
    checkbox.value = "value";
    checkbox.id = "id";

    var divElement = document.createElement("div");

    divElement.id = "myDiv";
    divElement.className = "myDivClass";
    divElement.style.border = "1px solid black";

    var userPar= document.createElement("p");

    userPar.innerHTML = firstname + " " +  lastname;
    document.getElementById("users").appendChild(divElement);
    divElement.appendChild(userPar);
    divElement.appendChild(checkbox);
}

function save() {
    $('input[type=checkbox]').each(function () {
        if (this.checked) {
            var first = firstname;
            var last = lastname;
            console.log(firstname);
            console.log(lastname);
        }
    });
}

最佳答案

尝试这个,

for (var i = 0; i<obj.length; i++) {
    firstname = obj[i].Firstname;
    lastname = obj[i].Lastname;

    var checkbox = document.createElement('input');

    checkbox.type = "checkbox";
    checkbox.name = "name";
    checkbox.value = "value";
    checkbox.id = "id" + i;

    var divElement = document.createElement("div");

    divElement.id = "myDiv" + i;
    divElement.className = "myDivClass";
    divElement.style.border = "1px solid black";

    var userPar= document.createElement("p");

    userPar.innerHTML = firstname + " " +  lastname;
    document.getElementById("users").appendChild(divElement);
    divElement.appendChild(userPar);
    divElement.appendChild(checkbox);
}

function save() {
    $('input[type=checkbox]').each(function (index, val) {
        if ($(val).is("checked")) {

            var RawText = $(val).parent().find("p").text();
            var first = RawText.split(" ")[0];
            var last = RawText.split(" ")[1];
            console.log(firstname);
            console.log(lastname);
        }
    });
}

09-18 05:57