【问题标题】:for each json result, add css with class jquery对于每个 json 结果,添加带有类 jquery 的 css
【发布时间】:2016-05-12 13:46:05
【问题描述】:

我正在尝试为我的网店中的过滤选项添加颜色。颜色代码正在保存,现在我通过 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>

类似的东西

【问题讨论】:

  • 如果你需要给元素添加一个新的类名,使用 .addClass("newClassname") 而不是把它当作属性。
  • 我的代码目前替换了现有的类,这就是我的意思。

标签: javascript jquery css json


【解决方案1】:
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');
    });
}

【讨论】:

    【解决方案2】:

    我认为我的方法是从 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(' '));
    

    类似的东西。您可能想先对其进行测试;)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-14
      • 1970-01-01
      • 2011-08-23
      • 1970-01-01
      • 2014-04-21
      • 2016-10-18
      • 2012-09-22
      相关资源
      最近更新 更多