Can't stop list dividers being treated as list items
Asked Answered
R

5

5
$(document).on("click", "li", function() {alert("A list item was clicked");} 

I'm using the above code to perform an action on every list item but list dividers are also proccing this event.

I managed to exclude my close button using

$(document).on("click", "li", function() {
    if (this.id !== "closeButton") {
        alert("A list item was clicked");
    }
});

however I can't stop it from occurring on list dividers. I've tried to no avail

$(document).on("click", "li", function() {
    if (this.class !== "ui-li-divider") {
        alert("A list item was clicked");
    }
});

Here's a JSFiddle with the problem: http://jsfiddle.net/2g3w5/

Roil answered 5/8, 2014 at 6:45 Comment(0)
B
5

Modify your selector to li:not([data-role='list-divider'])

$(document).on("click", "li:not([data-role='list-divider'])", function() {
    if (this.id !== "closeButton") {
        alert("A list item was clicked");
        //choosePageTypeToBuild();
   }
});

Demo

OR modify your selector to li:not([data-role='list-divider'], #closeButton) and get rid of if condition

$(document).on("click", "li:not([data-role='list-divider'], #closeButton)", function() {
    alert("A list item was clicked"); //Get rid of if condition
});

Demo

Also, make sure you use specific selectors, else the selector you are using will target ALL the li elements in your document.

So assign an id to the wrapper element and modify your selector accordingly.

Berlauda answered 5/8, 2014 at 6:48 Comment(0)
H
4

Use a flag class on items which are not clickable & change you script to this,

Here I am using 'stat' class as flag

$(document).on("click", "li", function() {
    if(!$(this).hasClass('stat')){
        alert("A list item was clicked");
   }
});

DEMO

Haroun answered 5/8, 2014 at 6:50 Comment(0)
B
1

because your divider is a 'li' element, Edit "li" -> "a" and see what happen

$(document).on("click", "a", function() {
    if (this.class !== "ui-li-divider") {
        alert("A list item was clicked");
    }
});
Barbra answered 5/8, 2014 at 6:50 Comment(0)
E
1

You can check for the data-role attribute too and find out that the item is not a list-divider

The sample code will be something like this

 $(document).on("click", "li", function () {
    if ($(this).attr('data-role') !== 'list-divider' && this.id !== "closeButton") {
        alert("A list item was clicked");

    }

});

JSFiddle Demo

Electromagnetism answered 5/8, 2014 at 6:54 Comment(0)
H
1

Use :not in jquery

$(document).on("click", "li:not('.ui-li-divider')", function() {
        alert("A list item was clicked");
        //choosePageTypeToBuild();
});

or check with hasClass in jquery

$(document).on("click", "li", function() {
    if (!$(this).hasClass("ui-li-divider")) {
        alert("A list item was clicked");
    }
});

DEMO

Hillary answered 5/8, 2014 at 6:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.