简体   繁体   English

根据布尔数组显示或隐藏jQuery元素

[英]Show or hide jQuery elements according to boolean array

So I have the following code : 所以我有以下代码:

function aFunction(obj, myData)
{
    $.ajax({
        type: "POST",
        url: 'myUrl',
        data: myData,
        async: true,
        dataType: 'json',
        success: function(data)
        {
            // ???
        }
    });
}

The data I receive (correctly) is an array of booleans. 我收到的data (正确)是一组布尔值。 Now I need to show the jQuery objects according to each boolean : the number of jQuery objects and the size of the array is the same. 现在我需要根据每个布尔值显示jQuery对象:jQuery对象的数量和数组的大小是相同的。

Now, the following works as my success callback : 现在,以下作为我的成功回调:

    success: function(data)
    {
        //obj.show();
        var pcom_array = $.makeArray(obj);

        for(var i = 0; i < data.length; i++)
        {
            console.log(pcom_array[i]);
            if(data[i] === true)
            {
                pcom_array[i].style.display = '';
            }
        }
    }

However, casting the jQuery object as an array and then iterating over the array doesn't feel very "jQuery-ish" to me. 但是,将jQuery对象作为一个数组进行转换然后遍历数组并不会让我觉得非常“jQuery-ish”。 Is there a jQuery method or some other way that could smplify this? 是否有一个jQuery方法或其他方式可以简化这个?

You can use .toggle() - assuming obj is a jQuery wrapper containing a set of targeted elements in the same order as in the data array 你可以使用.toggle() - 假设obj是一个jQuery包装器,它包含一组目标元素,其顺序与数据数组相同

success: function(data) {
    obj.each(function(idx, el){
        $(this).toggle(data[idx])
    }) 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM