无法阻止列表分隔符被视为列表项

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

我正在使用上述代码对每个列表项执行操作,但列表分隔符也会处理此事件。

我成功地排除了我的关闭按钮,使用方法如下:

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

然而,我无法阻止它在列表分隔符上发生。我已经尝试了但没有成功。
$(document).on("click", "li", function() {
    if (this.class !== "ui-li-divider") {
        alert("A list item was clicked");
    }
});

这里有一个JSFiddle的问题:http://jsfiddle.net/2g3w5/
5个回答

5

将您的选择器修改为 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();
   }
});

示例

者修改您的选择器为 li:not([data-role='list-divider'], #closeButton) 并且去掉 if 条件。

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

演示

此外,请确保使用具体的选择器,否则您使用的选择器将会选中文档中的所有li元素。

因此,给包裹元素分配一个id并相应地修改您的选择器。


4

对于无法点击的项目,请使用flag类,并将您的脚本更改为以下内容:

在此处,我使用'stat'类作为标志

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

DEMO


1
因为您的分隔符是一个'li'元素, 将"li"编辑为"a",看看会发生什么。
$(document).on("click", "a", function() {
    if (this.class !== "ui-li-divider") {
        alert("A list item was clicked");
    }
});

1
你可以检查 data-role 属性,以确定该项不是 list-divider
示例代码将类似于以下内容。
 $(document).on("click", "li", function () {
    if ($(this).attr('data-role') !== 'list-divider' && this.id !== "closeButton") {
        alert("A list item was clicked");

    }

});

JSFiddle演示


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

或者在 jQuery 中使用 hasClass 进行检查。
$(document).on("click", "li", function() {
    if (!$(this).hasClass("ui-li-divider")) {
        alert("A list item was clicked");
    }
});

演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接