简体   繁体   English

将 class 添加到第一个动态创建的 li 标签

[英]Adding class to first dynamically created li tag

I am creating <li> elements as shown below from some JSON response.我正在根据一些 JSON 响应创建<li>元素,如下所示。 The problem with the following creation is that I have fixed and same number of bootstrap classes defined for each <li> element.以下创建的问题是我为每个<li>元素定义了固定且相同数量的引导程序类。

If I want to add the class="active" in the first <li> tag and not in the remaining tags so that the declaration would look like the following for the first list element:如果我想在第一个<li>标记中添加class="active"而不是在其余标记中,那么第一个列表元素的声明如下所示:

<li role="presentation" class = "active" >.

Is it possible to achieve this?有可能实现这一目标吗?

for (var key in jsonData) {
           if (jsonData.hasOwnProperty(key)) {
             console.log(key + " -> " + jsonData[key].textName);
                
    $('#tabs').append('<li role="presentation" ><a data-toggle="tab" id="tab_'+jsonData[key].textName+'" href="#panel_'+jsonData[key].textName+'">'+jsonData[key].textName+'<span id="count_'+jsonData[key].textName+'" class="countLabel"></span></a></li>');
                                   
        }
                        
    }

You could simplify it and just use.first()你可以简化它,只使用 .first()

$('#tabs').html(
  Object.entries(jsonData).map(([key,value]) => `<li role="presentation">
    <a data-toggle="tab" id="tab_${value.textName}" href="#panel_${value.textName}">${value.textName}<span id="count_${value.textName}" class="countLabel"></span></a>
  </li>`).join("")
).first().addClass("active");

In my opinion it's better to use Object.keys to transform the object into an array and then use Array.forEach to perform an action on each member.在我看来,最好使用Object.keys将 object 转换为数组,然后使用Array.forEach对每个成员执行操作。

This has the advantage of giving you access to the index of the item being transformed.这样做的好处是可以让您访问正在转换的项目的索引。 You can then check if the index is 0 and add the active class to the element.然后您可以检查索引是否为 0,并将活动的 class 添加到元素中。

 const jsonData = { foo: { textName: 'foo' }, bar: { textName: 'bar' } } Object.keys(jsonData).forEach((key, index) => { $('#tabs').append(`<li role="presentation" class="${index === 0? 'active': ''}">${jsonData[key].textName}</li>`); })
 .active { color: red; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul id="tabs"></ul>

Since you did not show what the json data looks like (eg if its an array you could use map() method), The solution is to create a variable that holds the index and increment it on each loop or at least once.由于您没有显示 json 数据的样子(例如,如果它是一个数组,您可以使用map()方法),解决方案是创建一个变量来保存索引并在每个循环或至少一次循环中递增它。

var index = 0;    
for (var key in jsonData) {
   if (jsonData.hasOwnProperty(key)) {
        console.log(key + " -> " + jsonData[key].textName);
       if(index == 0){         
    $('#tabs').append('<li role="presentation" class="active">');
    index = 3;
          }else{
    $('#tabs').append('<li role = "presentation">');
      }            
    $('tabs').append('<a data-toggle="tab" id="tab_'+jsonData[key].textName+'" href="#panel_'+jsonData[key].textName+'">'+jsonData[key].textName+'<span id="count_'+jsonData[key].textName+'" class="countLabel"></span></a></li>');            
        }
                        
 }

Try this;尝试这个;

let isFirstRun = true, container = $('#tabs'); //cache container for better performance
for (var key in jsonData) {
  if (jsonData.hasOwnProperty(key)) {
    container.append('<li role="presentation" ' + (isFirstRun ? 'class="active" : ""') + ' ><a data-toggle="tab" id="tab_' + jsonData[key].textName +
      '" href="#panel_' + jsonData[key].textName + '">' + jsonData[key].textName + '<span id="count_' + jsonData[
        key].textName + '" class="countLabel"></span></a></li>');
    isFirstRun = false;
  }
}

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

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