是否有一种更简洁的方法来解析我的HTML数据

Is there a cleaner way to parse my HTML data?

本文关键字:方法 我的 数据 HTML 简洁 一种 是否      更新时间:2023-09-26

我目前通过附加HTML来填充列表框(以及其他东西)。我通过AJAX加载从JSON中获取PHP数据,这允许我在页面上更灵活地重新加载内容并减少不必要的页面加载。

function tracker_list(){
    //get a reference to the select element
    $list = $('#tracker_list');
    //remove entries
    $('#tracker_list').empty();
    //request the JSON data and parse into the select element
    $.ajax({
      url: 'data/JSON_dashboard.php',
      dataType:'JSON',
      success:function(data){ 
        //iterate over the data and append a select option
        $.each(data, function(key, val){
          $list.append('<li class="list-group-item"><div style="background: url('''+val.profile_photo_path+''');margin-right:10px;margin-left:7px" class="image-circle-30 pull-left"></div><span class="text-muted"><span class="glyphicon glyphicon-time timestamp pull-right" data-toggle="tooltip" data-placement="bottom" title="'+val.last_activity+'"></span></span><strong><a href="#">'+val.first_name+' '+val.last_name+'</a></strong> was on the <strong><a href="#">'+val.last_page+'</a></strong><br /><span class="text-muted small">'+val.since+'</span></li>'); 
          var total = val.total;
        $("#tracker_num").html("<strong>"+total+"</strong>");   // Replace total users number in head  
        })

      },
      error:function(){
      }
    });
    };

如果我要一直这样做,有没有更好的方法?只要我在所有HTML上使用新行,脚本就会中断,代码将开始变得相当难以读。

为了更干净,更有性能的方式。

HTML对每个元素的操作都是昂贵的。创建一个数组,推入其中,最后连接所有项。总计数可以在每次迭代之外。

function tracker_list() {
    //get a reference to the select element
    $list = $('#tracker_list');
    //request the JSON data and parse into the select element
    $.ajax({
        url: 'data/JSON_dashboard.php',
        dataType: 'JSON',
        success: function(data) {
            //remove entries
            $list.empty();
            var strArr = [];
            //iterate over the data and append a select option
            $.each(data, function(key, val) {
                strArr.push('<li class="list-group-item"><div style="background: url(''' + val.profile_photo_path + ''');margin-right:10px;margin-left:7px" class="image-circle-30 pull-left"></div><span class="text-muted"><span class="glyphicon glyphicon-time timestamp pull-right" data-toggle="tooltip" data-placement="bottom" title="' + val.last_activity + '"></span></span><strong><a href="#">' + val.first_name + ' ' + val.last_name + '</a></strong> was on the <strong><a href="#">' + val.last_page + '</a></strong><br /><span class="text-muted small">' + val.since + '</span></li>');
                .append();
            })
            $list.append(strArr.join(""));
            $("#tracker_num").html("<strong>" + data[data.length - 1].total + "</strong>"); // Replace total users number in head  
        },
        error: function() {}
    });
};

要添加换行符,您可以在另一个变量中构建HTML,并将其添加到HTML:

var html = '<li class="list-group-item"><div style="background';
html = html + 'url('''+val.profile_photo_path+''');margin-right';
html = html + '10px;margin-left:7px" class="image-circle-30 pull-left">';
// and so on...
$list.append(html)

或者,您可以像这样使用jQuery构建HTML(仅第一部分):

var html = $('<li />')
    .addClass('list-group-item')
    .append($('<div />')
        .css({
            background  : 'url('+val.profile_photo_path+')',
            marginRight : 10,
            marginLeft  : 7
        })
        .addClass('image-circle-30 pull-left')
    )
    .append($('<span />')
        .addClass('text-muted')
        .append($('<span />')
            .addClass('glyphicon glyphicon-time timestamp pull-right')
            .data({
                toggle  : 'tooltip',
                placement   : 'bottom'
            })
            .prop({
                title   : val.last_activity
            })
     );
  // and so on ...
  $list.append(html)

但我建议你使用像JSRender或Mustache这样的诱惑引擎。

是否有一个更干净的方式来解析我的HTML数据?

是的,这种更干净的方式被称为HTML模板,例如Handlebars.js。首先,将所需的HTML部分写入一个特殊的脚本标记中,并为想要显示的单个值提供占位符。

Total: <strong id="tracker_num"></strong>
<script type="text/x-handlebars-template" id="trackerlist-template">
  {{#each .}}
  <li class="list-group-item">
    <div class="profile-image" class="image-circle-30 pull-left" style="background-image: url('{{ profile_photo_path }}'); margin-right:10px; margin-left:7px;"></div>
    <span class="text-muted">
      <span class="glyphicon glyphicon-time timestamp pull-right" data-toggle="tooltip" data-placement="bottom" title="{{last_activity}}"></span>
    </span>
    <strong><a href="#">{{first_name}} {{last_name}}</a></strong> was on the
    <strong><a href="#">{{last_page}}</a></strong><br />
    <span class="text-muted small">{{since}}</span>
  </li>
  {{/each}}
</script>

然后你可以在JavaScript代码中使用该模板,而不必为创建HTML而烦恼,因为代码和表示是清晰分开的。

var trackerlistTemplate = Handlebars.compile( $("#trackerlist-template").html() );
function getTrackerList() {
    return $.get('data/JSON_dashboard.php').fail(function () {
        console.err("could not retrieve tracker list");
    });
}
function renderTrackerList(data) {
    $('#tracker_list').html( trackerlistTemplate(data) );
    $("#tracker_num").text(data.length);
}
$("#refreshButton").click(function () {
    getTrackerList().done(renderTrackerList);
});
指出

    对于这样一个简单的GET请求,您不需要使用$.ajax()$.get()要短得多,也会工作得很好。
  • 将获取数据的函数与处理数据的函数分开可能是有用的。这可以很容易地用jQuery实现,因为您可以从数据获取函数返回XHR对象,并在其他地方使用它,如上所示。