Turn a div into a button dynamically

2019-08-24 09:44发布

i don't seem to find any way to work this out..so i guess i m going to need some help.. i m making a phonegap application in which i have an sqlite database.I perform a query and get the results in a dynamically created div from the database, the thing is that i want for each record that i extract to make the div that contains it, as a button with an editable role..

for instance lets say that i have a db with these columns id option1 option2 and i have three records.. this means that i will have three divs i want, each div to be a button so that if user clicks on it to be able to perform a delete (or edit/update) query without being worried about id for instance, if he selects div2 do perform a query that will delete second record..

my code so far..

for (var i = 0; i < len; i++) {
    var test1 = results.rows.item(i).option1;
    var d = new Date();
    d.setTime(results.rows.item(i).date);
    var newLI = document.createElement("LI");
    newLI.className = lt;
    newLI.id = results.rows.item(i).id;
    var container = ("<div id=\"" + results.rows.item(i).id + "\" class=\"test\"><div id=\"text\">option1</div><div id=\"data\">" + test1 + "</div></div>");
    newLI.innerHTML = cont;
    var gl = document.getElementById("sqltest");
    gl.appendChild(newLI);
}
for (var i = 0; i < len; i++) {
    var divid = "#" + results.rows.item(i).id;
    $(divid).on("click", function () {
        alert(divid);
    })
}

<ul id="sqltest"></ul>

problem with above code, is that although each div gets the correct id, when i click on it, i always get the same result for instance #1 although i may have 3 divs.. instead of having as a result

div1 alert #1 div2 alert #2 

i get

div1 alert #1 div2 alert#1

I've used alert just to simplify it, instead of alert there will be DELETE from SQLDB WHERE id=results.rows.item(i).id;

1条回答
欢心
2楼-- · 2019-08-24 09:55

You are retreiving always the same 'divid' variable, because of the way javascript scope and closures work. This is a very common mistake. You can google "javascript closure infamous loop" to get more information about this.

You should replace your for with this:

for (var i = 0; i < len; i++) {

    (function () {
        var divid = "#" + results.rows.item(i).id;
        $(divid).on("click", function () {
            alert(divid);
        });
    })();
}

That way, the variable divid is declared in different scopes each time.

I didn't understand if that is the only problem you are having.

查看更多
登录 后发表回答