对于每个json结果,使用类jquery添加css

for each json result, add css with class jquery

本文关键字:jquery 添加 css 于每个 json 结果      更新时间:2023-09-26

我正试图在我的网店中添加一种颜色来过滤选项。颜色代码正在被保存,现在我通过json返回它们。我想做的是将颜色代码添加到输入上方的父类中。我发现了如何更改类名(出于其他原因我需要更改),但现在我必须添加颜色代码,以便json从上到下返回它们。

到目前为止,我得到的是:

    function onDataReceived(data) {
        for (var i = 0; i < data.colorInfo.length; i++) {
            console.log(data.colorInfo[i].colorCode);
        }
        $('input[id^="filter_"]').each(function(){
            $(this).parent().attr('class','addedClass');
            $(this).parent().parent().attr('class','addedClass');
        });
    }
    $(document).ready(function () {
            var url = 'myjsonlink.json';
            $.get(url, onDataReceived);
    });

带有console.log(data.colorInfo[i].colorCode)的行;结果中的3个颜色代码我需要#fff等。有没有办法插入以上3个输入类型的结果?

我想实现的是:

<div style="background-color: data.colorInfo[i].colorCode"> <input> </div>

类似的东西

function onDataReceived(data) {
    //for (var i = 0; i < data.colorInfo.length; i++) {
    //    console.log(data.colorInfo[i].colorCode);
    //}
    var len = data.colorInfo.length;
    $('input[id^="filter_"]').each(function(i){
        $(this).parent().addClass('addedClass');//attr('class','addedClass');
        $(this).parent().parent().addClass('addedClass')
               .css('background-color',"'" + data.colorInfo[i % len].colorCode + "'");
//.attr('class','addedClass');
    });
}

我认为我的方法是从DOM元素中获取具有类名的字符串:

var classString = $(this).parent().attr('class','addedClass');

然后将其拆分,并在其中循环:

var newClasses = []; //initalize the new classes array
var classes = classString.split(/ /);
for(var a=0; a<classes.length; a++){
    var colorObj = data.colorInfo[a]; //get the relevant color object
    if(colorObj){
        newClasses.push(classes[a] + '-' + colorObj.colorCode); //
    }
}

然后用新创建的类替换旧类:

$(this).parent().attr('class', newClasses.join(' '));

类似的东西。你可能想先测试一下;)