javascript - 对于这种情况,在 DOM 中动态添加这些元素的权利是什么?

标签 javascript jquery html

我有一个网站,其中有一个列表,如图所示。现在,有两种方法可以为每个用户添加这些列表项。

一个(见示例 1)是使用纯 JavaCript 和 jQuery。 另一个(见示例 2)使用字符串连接。

对于每个列表项,我必须运行一个 for 循环。所以我认为可能至少有 2 个问题与速度、性能和易用性有关。

首先,考虑到速度和性能,我需要选择其中之一。 其次,如果您看到示例1,我会“选择并删除每个最小的元素,我必须记住谁是父元素,谁是子元素。此外,我必须小心地添加 classesattributes 以更正父级。但是在示例 2 中,HTML 就在您面前。所以我不需要太多记住这些事情。

那么这只是我的想法中的“轻松”事情还是我真的做错了什么?

示例 1:JavaScript/jQuery

function createListItem(todo, count) {
li = '';
var li = document.createElement('li');
li.id = "user" + count + " user_" + todo.userid;
li.className = "user user_" + todo.userid;

var item = document.createElement('div');
item.className = 'item';


var inner = document.createElement('div');
inner.className = 'inner';
inner.style.cssText = 'height:86px';

var item_specific = document.createElement('div');
item_specific.className = 'item-specific2 item-specific';
/*battery*/
var device_battery = document.createElement('span');
device_battery.id = 'device_battery' + count;
device_battery.className = 'device_battery';
device_battery.title = 'Device Battery Status';
fa_bolt = document.createElement('i');
fa_bolt.className = 'fa ' + ' ' + todo.bolt;
fa_bolt.style.cssText = 'color: white !important;opacity: 1 !important;';
battery_percent = document.createElement('i');
battery_percent.className = 'fa ' + todo.battery_life + '';
device_battery.append(fa_bolt)
device_battery.append(battery_percent)
device_battery.append(todo.battery + '%')
/*Device status*/
var device_status = document.createElement('span');
device_status.id = 'device_status' + count;
device_status.className = 'device_status';
device_status.title = 'Device Battery Status';
fa_bolt = document.createElement('i');
fa_bolt.className = 'fa ' + todo.circleforonline;
device_status.append(fa_bolt)
device_status.append(todo.status)
/*Employee status*/
var employee_status = document.createElement('span');
employee_status.id = 'employee_status' + count;
employee_status.className = 'employee_status';
employee_status.title = 'Internet & GPS Status';
fa_bolt = document.createElement('i');
fa_bolt.className = 'fa ' + todo.circleforcharging;
employee_status.append(fa_bolt)
employee_status.append(todo.is_charging)
/*Employee Image*/
mCS_img_loaded = document.createElement('IMG')
mCS_img_loaded.className = 'mCS_img_loaded';
mCS_img_loaded.id = 'img_src' + count + '';
mCS_img_loaded.style.cssText = 'float: left';
mCS_img_loaded.src = todo.img_path;
$("img").error(function () {
//console.log('image')
//$(this).unbind("error").attr("src", "assets/img/items/real-estate/6.jpg");
})
/*Employee name*/
delivery_boy_name = document.createElement('div');
delivery_boy_name.className = 'delivery_boy_name dely_boy pan-to-marker';
delivery_boy_name.setAttribute("data-wholedata", count)
delivery_boy_name.setAttribute("data-userid", todo.userid)
delivery_boy_name.setAttribute("data-marker-lat", todo.lang)
delivery_boy_name.setAttribute("data-marker-lng", todo.lng)
delivery_boy_name.setAttribute("data-marker-index", count)
delivery_boy_name.addEventListener("click", view_orders_click);
h3_name = document.createElement('h3');
h3_name.append(todo.fname + ' ' + todo.lname)
delivery_boy_name.append(h3_name)
/*Employee Estimate time*/
estimate = document.createElement('div')
estimate_text = document.createElement('div')
estimate_text.style.cssText = 'float: left;';
estimate_text.id = 'eta_' + todo.userid + '';
estimate.className = 'row eta estimate';
estimate.setAttribute("data-userid", todo.userid)
estimate.addEventListener("click", view_estimate_click);
estimate_div = document.createElement('div')
estimate_div.style.cssText = 'float: left;background: #0f9595;font-size: 14px;color: #fff;margin-left: 15px;padding: 0 4px;width:20px;border-radius: 50%;margin-right: 5px;';
fa_bolt = document.createElement('i');
fa_bolt.className = 'fa fa-refresh';
estimate_text.append('ETA')
estimate_div.append(fa_bolt)
estimate.append(estimate_div)
estimate.append(estimate_text)
/*Assign button*/
assign_resposnive = document.createElement('div')
assign_resposnive.className = 'price price2 assign_resposnive'
assign_resposnive.setAttribute("data-mobile", todo.mobile)
assign_resposnive.setAttribute("data-userid", todo.userid)
anchor_order = document.createElement('a')
anchor_order.className = 'assign_order'
anchor_order.setAttribute("href", '#assign_order')
anchor_order.setAttribute("data-toggle", 'toggle')
anchor_order.setAttribute("data-mobile", todo.mobile)
anchor_order.setAttribute("data-userid", todo.userid)
anchor_order.style.cssText = 'color:white;font-size: 10px;';
assign_resposnive.append(anchor_order)
assign_resposnive.addEventListener("click", assign_button_click);
anchor_order.append('ASSIGN')
/*View order button*/
view_orders = document.createElement('div')
view_orders.className = 'view_orders pan-to-marker'
view_orders.setAttribute("data-wholedata", count)
view_orders.setAttribute("data-userid", todo.userid)
view_orders.setAttribute("data-marker-lat", todo.lang)
view_orders.setAttribute("data-marker-lng", todo.lng)
view_orders.setAttribute("data-marker-index", count)
get_assigned_data = JSON.search(store.getAll().get_assigned_data, '//*[dbid="' + todo.userid + '" and order_status="A"]');
view_orders.addEventListener("click", view_orders_click);
view_orders.append('VIEW ORDERS(' + (get_assigned_data).length + ')')
/*view geofence button*/

view_geofence = document.createElement('div')
view_geofence.className = 'view_orders  view_geofence_ '
view_geofence.setAttribute("data-fname", todo.fname)
view_geofence.setAttribute("data-geo_latitude", todo.geo_latitude)
view_geofence.setAttribute("data-geo_longitude", todo.geo_longitude)
view_geofence.setAttribute("data-geo_radius", todo.geo_radius)
view_geofence.setAttribute("data-wholedata", count)
view_geofence.setAttribute("data-userid", todo.userid)
view_geofence.setAttribute("data-marker-lat", todo.lang)
view_geofence.setAttribute("data-marker-lng", todo.lng)
view_geofence.setAttribute("data-marker-index", count)
view_geofence.addEventListener("click", view_geofence_click);
view_geofence.append('VIEW GEOFENCE')

item_specific.append(device_battery)
item_specific.append(device_status)
item_specific.append(employee_status)
inner.append(item_specific)
inner.append(mCS_img_loaded)
inner.append(delivery_boy_name)
inner.append(assign_resposnive)
inner.append(view_orders)
if (todo.geo_latitude && todo.geo_longitude && todo.geo_radius) {
inner.append(view_geofence)
}
li.append(item)
item.append(inner)
item.append(estimate)

return li;
}

示例 2:串联

dataHtml += '<li id="' + i + '"><div class="item" id="' + i + '"><div class="inner" style="height:86px"><div class="item-specific2 item-specific"><span title="Device Battery Status" id="device_battery' + i + '" class="device_battery"><i class="fa ' + bolt + '" style="color: white !important;opacity: 1 !important;"></i><i class="fa ' + battery_life + '"></i>' + path_map[i]['battery'] + '%</span><span class="device_status" id="device_status' + i + '" title="Internet & GPS Status"><i class="' + circleforonline + '"></i>' + status + '</span><span class="employee_status" id="employee_status' + i + '" title="Internet & GPS Status"><i class="' + circleforcharging + '"></i>' + is_charging + '</span></div><img class="mCS_img_loaded" id="img_src' + i + '" style="float:left" src="' + imgUrl + '" alt=""><a  data-target="" class=" " style=""  ><div class="delivery_boy_name dely_boy pan-to-marker" data-wholedata="' + i + '" data-userID=' + path_map[i]['userid'] + '  data-marker-lat="' + path_map[i]['lang'] + '" data-marker-lng="' + path_map[i]['lng'] + '" data-userID=' + path_map[i]['userid'] + '   data-marker-index="' + i + '"><h3>' + path_map[i]['fname'] + ' ' + path_map[i]['lname'] + '</h3></div></a><div data-mobile="' + path_map[i]['mobile'] + '" data-userid="' + path_map[i]['userid'] + '" class="price price2 assign_resposnive" style=""><a href="#assign_order" class="assign_order" style="color:white;font-size: 11px;" data-toggle="modal" data-mobile=' + path_map[i]['mobile'] + ' data-userid="' + path_map[i]['userid'] + '" data-target="" >ASSIGN </a></div><div class="view_orders pan-to-marker" data-wholedata="' + i + '" data-userID=' + path_map[i]['userid'] + '  data-marker-lat="' + path_map[i]['lang'] + '" data-marker-lng="' + path_map[i]['lng'] + '" data-userID=' + path_map[i]['userid'] + '   data-marker-index="' + i + '">VIEW ORDERS(' + (get_assigned_data).length + ')</div>' + geofence + '<div class="arrow_img"></div></div><div class="row eta estimate" data-userID=' + path_map[i]['userid'] + ' style=""><div style="float: left;background: #0f9595;font-size: 14px;color: #fff;margin-left: 15px;padding: 0 4px;width:20px;border-radius: 50%;margin-right: 5px;"><i  class="fa fa-refresh " aria-hidden="true" style="font-size:13px;"></i></div><div style="float:left" id="eta_' + path_map[i]['userid'] + '">ETA</div></div><div class="wrapper expandable-content show-0 collapsed " id="wrapper_id' + i + '"><a href="#assign_order"  style="" data-toggle="modal" data-wholedata="' + i + '" data-userID=' + path_map[i]['userid'] + '  data-marker-lat="' + path_map[i]['lang'] + '" data-marker-lng="' + path_map[i]['lng'] + '"   data-marker-index="' + i + '"  data-target="" class="pan-to-marker " style="" ></a><table><tr><td class="td-35-icon"><div class="fa fa-phone"></div></td><td class="td-35">' + path_map[i]['mobile'] + '</td></tr><tr style="border-left: 1px solid #000;"><td class="fa fa-map-marker td-80-icon" style="padding-top:34px"></td><td class="td-80"><div id="addrss' + i + '"></div></td></tr><tr><td class="td-35-icon"> <div class="fa fa-clock-o" ></td><td  class="td-35"> </td></tr></table></div></div></li>';

输出:

enter image description here

注意:示例 2 没有创建与示例 1 相同的文本和按钮。基本上结构相同。回答时应将它们视为相同。

最佳答案

看起来您有一个相当大的 HTML block 可以重复并填充您在对象数组中的信息。

您尝试过的两个选项难以阅读...因此难以维护。

这是我使用 jQuery 的方法。
所以首先,这假设一个对象数组如下所示:

var path_map=[
  {
    battery:"79",
    userid:9876,
    lang:40.730610,
    lng:-73.935242,
    fname:"John",
    lname:"Doh",
    mobile:"555-555-5555",
    bolt:"fa-bolt",
    battery_life:"fa-battery-three-quarters green",
    circleforonline:"fa-circle green",
    status:"online",
    circleforcharging:"fa-circle orange",
    is_charging:"charging"
  },{
    battery:"50",
    userid:5656,
    lang:40.730610,
    lng:-73.935242,
    fname:"Johnny",
    lname:"Deeh",
    mobile:"555-555-4444",
    bolt:"fa-bolt",
    battery_life:"fa-battery-half orange",
    circleforonline:"fa-circle green",
    status:"online",
    circleforcharging:"fa-circle orange",
    is_charging:"charging"
  },{
    battery:"10",
    userid:5656,
    lang:40.730610,
    lng:-73.935242,
    fname:"Suzy",
    lname:"Sheer",
    mobile:"555-555-7777",
    bolt:"fa-bolt",
    battery_life:"fa-battery-quarter red",
    circleforonline:"fa-circle green",
    status:"online",
    circleforcharging:"fa-circle orange",
    is_charging:"charging"
  }
];

现在我将在我的 HTML 文档正文中键入一个 li 并使用 id 将其设置为隐藏。
我们称它为#clone...因为这个“空”li 将永远不会显示。
它是一个"template",可以在将遍历您的对象的 for 循环中克隆。

在循环中,我会在必须插入的地方插入信息。
然后,我会将这个克隆的 li 附加到 ul
更改后的 id 将使其可见。

代码看起来像这样(更具可读性):

for(i=0;i<path_map.length;i++){
  var myClone = $("#clone").clone();

  myClone.attr("id",i);

  myClone.find(".device_battery").append(path_map[i]["battery"]+"%");
  myClone.find(".device_battery").find("i").eq(0).addClass(path_map[i]["bolt"]);
  myClone.find(".device_battery").find("i").eq(1).addClass(path_map[i]["battery_life"]);
  myClone.find(".device_status").append(path_map[i]["status"]);
  myClone.find(".device_status").find("i").addClass(path_map[i]["circleforonline"]);
  myClone.find(".employee_status").append(path_map[i]["is_charging"]);
  myClone.find(".employee_status").find("i").addClass(path_map[i]["circleforcharging"]);
  myClone.find(".employee_name").append(path_map[i]["fname"]+" "+path_map[i]["lname"]);
  myClone.find(".employee_mobile").append(path_map[i]["mobile"]);

  $("ul").append(myClone);
}



简而言之,我会将“简单”HTML 与用于向其中插入数据的代码分开。

看看下面的片段和/或这个CodePen .

var path_map=[
  {
    battery:"79",
    userid:9876,
    lang:40.730610,
    lng:-73.935242,
    fname:"John",
    lname:"Doh",
    mobile:"555-555-5555",
    bolt:"fa-bolt",
    battery_life:"fa-battery-three-quarters green",
    circleforonline:"fa-circle green",
    status:"online",
    circleforcharging:"fa-circle orange",
    is_charging:"charging"
  },{
    battery:"50",
    userid:5656,
    lang:40.730610,
    lng:-73.935242,
    fname:"Johnny",
    lname:"Deeh",
    mobile:"555-555-4444",
    bolt:"fa-bolt",
    battery_life:"fa-battery-half orange",
    circleforonline:"fa-circle green",
    status:"online",
    circleforcharging:"fa-circle orange",
    is_charging:"charging"
  },{
    battery:"10",
    userid:5656,
    lang:40.730610,
    lng:-73.935242,
    fname:"Suzy",
    lname:"Sheer",
    mobile:"555-555-7777",
    bolt:"fa-bolt",
    battery_life:"fa-battery-quarter red",
    circleforonline:"fa-circle green",
    status:"online",
    circleforcharging:"fa-circle orange",
    is_charging:"charging"
  }
];

for(i=0;i<path_map.length;i++){
  var myClone = $("#clone").clone();

  myClone.attr("id",i);

  myClone.find(".device_battery").append(path_map[i]["battery"]+"%");
  myClone.find(".device_battery").find("i").eq(0).addClass(path_map[i]["bolt"]);
  myClone.find(".device_battery").find("i").eq(1).addClass(path_map[i]["battery_life"]);
  myClone.find(".device_status").append(path_map[i]["status"]);
  myClone.find(".device_status").find("i").addClass(path_map[i]["circleforonline"]);
  myClone.find(".employee_status").append(path_map[i]["is_charging"]);
  myClone.find(".employee_status").find("i").addClass(path_map[i]["circleforcharging"]);
  myClone.find(".employee_name").append(path_map[i]["fname"]+" "+path_map[i]["lname"]);
  myClone.find(".employee_mobile").append(path_map[i]["mobile"]);

  $("ul").append(myClone);
}
ul {
  list-style-type: none;
}
.green{
  color:green;
}
.orange{
  color:orange;
}
.red{
  color:red;
}
#clone{
  display:none;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<ul>
  <li id="clone">
    <div class="item" id="123123">
      <div class="inner" style="height:86px">
        <div class="item-specific2 item-specific">
          <span title="Device Battery Status" id="device_battery123123" class="device_battery">
            <i class="fa"></i>
            <i class="fa"></i>
          </span>
          <span class="device_status" id="device_status123123" title="Internet & GPS Status">
            <i class="fa"></i>
          </span>
          <span class="employee_status" id="employee_status123123" title="Internet & GPS Status">
            <i class="fa"></i>
          </span>
        </div>
        <div class="employee_name"></div>
        <div class="employee_mobile"></div>
      </div>
    </div>
  </li>
</ul>

顺便说一句,最好为每个“占位符”设置一个特定的,这样可以省去所有额外的.find() .eq()。我只是让这个示例看起来像您的 HTML。

关于javascript - 对于这种情况,在 DOM 中动态添加这些元素的权利是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44815592/

相关文章:

css - 如何使打印页面的背景与其他打印页面不同?

javascript - 如何在没有垂直间隙的情况下 float 元素?

html - 帮助缩小表大小

javascript - 如何使用 NodeJS 在 Windows 和 Linux 机器上读取同一项目中的绝对路径?

javascript - 使用 PHP 创建一个新的 PHP 文件

javascript - Dojo 教程 - 业务应用程序架构

javascript - 绝对定位时div消失,父级动态高度

javascript - jquery.find()在ie中返回null,但在其他浏览器中不返回

jquery - 通过遍历class来查找id

javascript - 两个内联 block div 的垂直对齐