javascript - 为什么我的 jquery 删除列表中的第一个元素而不是指定的元素?

标签 javascript jquery html html-lists

我正在尝试使用 .each() 循环遍历 html 中的列表,并删除具有匹配 id 的任何元素。

<ul>
<li id="0" class="liRem">zero</li>
<li id="1" class="liRem">one</li>
<li id="2" class="liRem">two</li>
<li id="3" class="liRem">three </li>
<li id="4" class="liRem">four </li></ul>

还有 jquery:

var output = [1, 3];
$(document).ready(function () {
    $("ul li").each(function () {
        if(this.id in output) {
            $(this).remove();
        };
    });
});

但是,它只是删除页面上的下一个“第一个”元素,而不是删除指定的 li 元素。

另外,我无法改变我正在使用数组的事实,并且该列表是 html 文档中唯一的列表。我是 jquery 新手,所以任何建议将不胜感激

最佳答案

Javascript 没有“数组中的值”功能。这用于 for 循环来遍历对象的每个元素。

相反,您应该使用 JQuery inArray method或 array.indexOf(value) > -1。 此外,Id 是字符串,而数组包含数字。

这有效:

var output = ["1", "3"];
$(document).ready(function () {
    $("ul li").each(function () {
        if(output.indexOf(this.id) > -1) {
            $(this).remove();
        };
    });
});

https://jsfiddle.net/07atsh5o/

关于javascript - 为什么我的 jquery 删除列表中的第一个元素而不是指定的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33253222/

相关文章:

javascript - 悬停覆盖且不影响文本颜色

javascript - 使用关键字搜索 JSON 结果集并仅返回匹配项

javascript - 如何让点击div时出现弹出框?

javascript - JQuery 可以在预览版中使用,但不能在 Tumblr 上使用

html - 太长而无法放在一行中的元素没有额外的行高吗?

javascript - 如果 body 具有淡入 mp3 声音的类,否则淡出

javascript - 在 if 条件中使用 .hasClass() 不起作用

javascript - 如何在页面加载时在 HtmlEditorExtender 中设置内容

html - 如何在 Outlook 2010、Outlook 2007、Outlook 2013 中的图像顶部的文本上提供填充/边距?

javascript - Angular ng-repeat 不会为动态创建的数组绑定(bind)数据