javascript - jQuery - 如何选择具有相同类但不具有特定 ID 的所有元素

标签 javascript jquery html

这是我的代码:

$( "#targetButton" ).click(function() {
        $.ajax({
            url: './checkcolors.php',
            type: 'post',
            data: {
                url: 'http://www.sportsdirect.com/dunlop-mens-canvas-low-top-trainers-246046?colcode=24604622',
                SizeId: '6.5'
            },
            dataType: 'text',
            success: function (data) {
                var arr = data.split(',');
                arr.forEach(function(id){
                    $('#' + id.trim()).show();
                });
            }
        });
}); 

这是一个 ajax post 函数,如果 ids 则返回一个数字。 返回的 id 正在响应我必须显示的 div html 元素。 这些 html div 元素具有相同的类,但它们都具有不同的 id。

所以我尝试使用此代码来选择具有相同类的所有元素,但排除具有指向的 id 的元素:

$('.ColorImagesNOColor:not(#' + id.trim() + ')').show();

它似乎不起作用,因为它显示了此类的所有元素,即使具有不得显示的 id。

你能帮我一下吗?

提前致谢!

最佳答案

您正在 .forEach 循环内执行此操作。这意味着最后一个 $('.ColorImagesNOColor:not(#' + id.trim() + ')').show(); 将确定 .ColorImagesNOColor 的最终可见性 元素。

如果您想显示所有 .ColorImagesNOColor 元素并隐藏返回 id 的元素,那么您可以将第一步移至 .forEach 循环之前:

// Show all initially
$('.ColorImagesNOColor').show();

// Hide ones with certain Id's
arr.forEach(function(id){
    $('#' + id.trim()).hide();
});

关于javascript - jQuery - 如何选择具有相同类但不具有特定 ID 的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32121345/

相关文章:

javascript - 使用 .position() 查找元素在 jquery 中的位置不起作用

使用 apply() 函数的 JavaScript 函数构造函数链接

javascript - 如何将 "Create an account"表单设为此 codepen 的默认 View ?

javascript - 如何在不刷新页面的情况下在前端显示更新的数据?

javascript - 如何避免 React fetch API 替换 url

javascript - 如何区分数组和数组的数组

javascript - 在 Laravel 中安装后如何需要 npm 包?

javascript - 防止jquery计算后出现负值

javascript - jQuery 选择 : select 1 option and deselect the same option in another select menu

javascript - 使用 MYSQL 防止已选择的选项 Jquery 自动完成