对于每个json结果,使用类jquery添加css
for each json result, add css with class jquery
我正试图在我的网店中添加一种颜色来过滤选项。颜色代码正在被保存,现在我通过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(' '));
类似的东西。你可能想先测试一下;)
相关文章:
- JQuery添加元素需要在我的js之前再次添加JQuery脚本
- 通过jQuery添加ng样式属性,angular不更新
- 使用HTML5 localStorage和jQuery添加到收藏夹/书签
- jQuery添加的文本不显示
- 使用Jquery添加内容
- 如何使用jQuery添加另一个对象的高度作为边距
- JavaScript/jQuery-添加添加和删除类与下一个函数之间的延迟
- 对于每个json结果,使用类jquery添加css
- Jquery添加一个类之后,如何应用css
- 使用jQuery添加和删除属性
- Jquery添加输入字段和日期选择器
- jQuery - 添加删除类 - 设置输入值
- 为什么在这种情况下要向JQuery添加两个链接
- 为图像滑块jquery添加项目符号功能
- 使用jquery添加到表单内部表中的元素不会过帐
- 如何使用jquery添加元素
- 使用Jquery添加XML元素
- 当使用javascript/jquery添加值时,html文本输入表显示不正确
- 将jquery添加到firefox扩展中
- 运行 AJAX 需要什么 - 将 jQuery 添加到页面处理 AJAX 调用