【问题标题】:Adding Classes to Dynamic JSON Values向动态 JSON 值添加类
【发布时间】:2021-02-12 15:40:20
【问题描述】:

我有一个不同行业的动态用户列表,根据他们的行业(健康、教育、建筑、科学等),我想添加一个根据行业动态显示的颜色徽章用户在,以便快速区分用户,一目了然。当在硬编码的 html 环境中定位文本值时,该代码运行良好,但在尝试引用从动态 JSON 加载的文本值时似乎崩溃了。

我已经包含了下面的代码。

任何帮助将不胜感激!

谢谢, 史蒂夫。

//THIS IS THE CODE TO REFERENCE EXTERNAL JSON FILE
var userJSON = 'https://mighty-oasis-08666.herokuapp.com/users'

//THIS IS THE CODE TO FETCH EXTERNAL JSON FILE
$.getJSON(userJSON, function (populateUsers) {

    //THIS IS THE CODE TO POPULATE JSON DATA INTO TEMPLATE LITERAL CARD
    var userCard = populateUsers.reduce((acc, {id, name, username, email, phone, company, industry}) =>
            acc += `
            <div class='col col-4 align-items-stretch strain-container'>
                <div id="${id}" class="card user-card">
                    <div class="card-body">
                        <h2 class="title">${name}</h2>
                        <h6 class="title">${username}</h6>
                        <h6 class="title">${email}</h6>
                        <h6 class="title">${phone}</h6>
                        <h6 class="title">${company}</h6>
                        <h6 class="industry-type title">${industry}</h6>
                    </div>
                </div>
            </div>`
    , ``);
    $('#user-grid').append(userCard)
});

//THIS IS THE CODE TO TARGET INDUSTRY TYPE CLASS
var $industryType = $('.industry-type');

//THIS IS THE CODE TO ADD INDUSTRY BADGE BASED ON INDUSTRY TYPE TEXT VALUE
$industryType.each(function() {
    var $this = jQuery(this);
    if ($this.text().trim() == 'Health') {
        $this.addClass('health-badge');
    } else if ($this.text().trim() == 'Education') {
        $this.addClass('education-badge');
    } else if ($this.text().trim() == 'Construction') {
        $this.addClass('construction-badge');
    } else if ($this.text().trim() == 'Science') {
        $this.addClass('science-badge');
    }
});
.health-badge {
    background-color: purple;
    color: green;
    height: 80px;
    width: 80px;
}
.science-badge {
    background-color: black;
    color: yellow;
    height: 80px;
    width: 80px;
}
.construction-badge {
    background-color: blue;
    color: white;
    height: 80px;
    width: 80px;
}
.education-badge {
    background-color: orangered;
    color: black;
    height: 80px;
    width: 80px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

    
<body>

<!-- USER GRID -->
<div id="user-grid" class="row container fluid-container"></div>   

</body>

【问题讨论】:

  • 如何分解?你是说你已经查看了 DOM 并且没有添加类吗?此外,旁注:任何时候你发现自己在编写大量重复的代码时,总是怀疑有更好的方法。
  • 在回调函数中添加新元素后需要执行$.each()循环。
  • @Mitya 正确,没有添加课程,例如,如果您在此处将“education-badge”直接添加到检查器中
    教育
    它看起来是正确的,但我无法将这些行业徽章类附加到动态生成的文本值。但就像我说的,当它们是硬编码的文本值时,代码可以工作......
  • @Barmar 我将如何在代码中执行此操作?

标签: jquery json template-literals json-value dynamic-class


【解决方案1】:

添加新元素时添加类。

您可以使用一个对象来保存行业名称和相应徽章类之间的映射,因此您不需要所有这些if 语句,并且可以将其用于静态和动态代码。

const industry_class = {
  "Health": "health-badge",
  "Education": "education-badge",
  "Construction": "construction-badge",
  "Science": "science-badge"
};

//THIS IS THE CODE TO REFERENCE EXTERNAL JSON FILE
var userJSON = 'https://mighty-oasis-08666.herokuapp.com/users'

//THIS IS THE CODE TO FETCH EXTERNAL JSON FILE
$.getJSON(userJSON, function(populateUsers) {

  //THIS IS THE CODE TO POPULATE JSON DATA INTO TEMPLATE LITERAL CARD
  var userCard = populateUsers.map(({id, name, username, email, phone, company, industry}) => {
    let cls = industry_class[industry.trim()] || "";
    return `
            <div class='col col-4 align-items-stretch strain-container'>
                <div id="${id}" class="card user-card">
                    <div class="card-body">
                        <h2 class="title">${name}</h2>
                        <h6 class="title">${username}</h6>
                        <h6 class="title">${email}</h6>
                        <h6 class="title">${phone}</h6>
                        <h6 class="title">${company}</h6>
                        <h6 class="industry-type title ${cls}">${industry}</h6>
                    </div>
                </div>
            </div>`;
  }).join("");
  $('#user-grid').append(userCard)
});

var $industryType = $('.industry-type');

$industryType.each(function() {
  var $this = jQuery(this);
  let industry = $this.text().trim();
  if (industry in industry_class) {
    $this.addClass(industry_class[industry]);
  }

});
.health-badge {
  background-color: purple;
  color: green;
  height: 80px;
  width: 80px;
}

.science-badge {
  background-color: black;
  color: yellow;
  height: 80px;
  width: 80px;
}

.construction-badge {
  background-color: blue;
  color: white;
  height: 80px;
  width: 80px;
}

.education-badge {
  background-color: orangered;
  color: black;
  height: 80px;
  width: 80px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>


<body>

  <!-- USER GRID -->
  <div id="user-grid" class="row container fluid-container"></div>

</body>

【讨论】:

  • 一百万谢谢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-05
  • 2016-06-15
  • 2021-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多