user2066880
user2066880

Reputation: 5024

Bind list element to tap JQuery Mobile

I have a function that renders a simple list using JQuery Mobile.

function() {
    var view = $("#test-content");
    view.empty();
    console.log(view);
    var ul = $("<ul></ul>").appendTo(view);

    for(var i=1; i <= 5; i++) {
        $("<li id=\"item" + i + "\">Item " + i + "</li>").appendTo(ul);
    }
    ul.listview();
}

How do I bind each element such that when it is tapped, it changes themes?

I tried adding the following code in the for loop, but it doesn't do anything.

$("#item" + i).bind("tap", function() {
            $(this).attr("data-theme", "e"); 
        });

Upvotes: 1

Views: 603

Answers (1)

Adil
Adil

Reputation: 148180

You missed the # for id selector also ensure the element with id item are added before binding event.

$("#item" + i).bind("tap", function() {
        $(this).attr("data-theme", "e");     
});

You may use on() for dynamically added elements. You can delegate the event to parent of dynamically added elements or to document.

$(document).on("tap", "id^=item", function() {
     $(this).attr("data-theme", "e"); 
});

Upvotes: 2

Related Questions