Question

Is there any way to create a listview in Jquery Mobile that has clickable list items and each item has 3 buttons? I don't want to use split-button listview. I have tried to create this but button clicks are not working. Clicking on any of the button behaves like clicking on list item.

Était-ce utile?

La solution

You can add e.stopImmediatePropagation(); (http://api.jquery.com/event.stopimmediatepropagation/) to the button clicks so they will not propagate to the parent listitem.

UPDATE:

OP mentioned in comments that listitems are generated dynamically. The original code still works because event delegation (https://learn.jquery.com/events/event-delegation/) was used for the buttons. Here is an updated example:

Empty UL in markup

<ul data-role="listview" id="thelist">
</ul>

On pagecreate, fill the listview and add the click handlers

$(document).on("pagecreate", "#page1", function(){

    //make list dynamically
    var allItems = '';
    for (var i=0; i< 4; i++){
         allItems += '<li data-rowid="' + i + '"><a href="#"><div data-role="controlgroup" data-type="horizontal"><input type="button" value="Hmm" /><input type="button" value="No" /><input type="button" value="Yes" /></div>&nbsp;Item ' + i + ' text or description</a></li>';   
    }
    $("#thelist").empty().append(allItems).listview("refresh").enhanceWithin();


    $("#thelist").on("click", "li input", function(e){
        e.stopImmediatePropagation();        
        var rowid = $(this).parents("li").data("rowid");
        var btnText = $(this).val();
        alert("You clicked the button: " + btnText + " on row number: " + rowid);
    });

    $("#thelist").on("click", "li a", function(e){
        alert("You clicked the listitem");
    });

});

Updated DEMO

ORIGINAL:

DEMO

<ul data-role="listview" id="thelist">
    <li data-rowid="1">
        <a href="#">            
            <div data-role="controlgroup" data-type="horizontal">
                <input type="button" value="Hmm" />
                <input type="button" value="No" />
                <input type="button" value="Yes" />
            </div>
            Item 1 text or description
        </a>
    </li>
</ul>

$(document).on("pagecreate", "#page1", function(){

    $("#thelist li").on("click", "input", function(e){
        e.stopImmediatePropagation();        
        var rowid = $(this).parents("li").data("rowid");
        var btnText = $(this).val();
        alert("You clicked the button: " + btnText + " on row number: " + rowid);
    });

    $("#thelist li").on("click", "a", function(e){
        alert("You clicked the listitem");
    });

});

You could also put the buttons outside of the listitem anchor tag and use CSS to position everything nicely...

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top