简体   繁体   English

使用jQuery创建动态div

[英]Creating dynamic div with jQuery

I am using jQuery ajax to fetch JSON data. 我正在使用jQuery ajax来获取JSON数据。

Below is my code sample. 下面是我的代码示例。 This is my jsfiddle. 是我的傻瓜。

Now lot of people told me that making dynamic string is not good. 现在很多人告诉我,制作动态字符串并不好。

Can somebody give me a better way to create a div ? 有人能给我一个更好的创建div吗?

$.ajax({
  url: 'https://api.myjson.com/bins/1mkxw',
  method: "GET",
  headers: { "Accept": "application/json; odata=verbose" },
  async: false,
  success: function (data) {
    let html;
    $.each(data.results, function (i, item) {
      html += '<div class="tileBlock"><img src="/PublishingImages/' + item.Title + '" alt="' + item.To.Title + '" /><br>';
      html += '<div class="blockCol1 greyLabel">' + item.To.Title + '</div><div class="blockCol2 fareTxt">' + item.Cost + '&nbsp;' + item.From.Currency + '</div><div style="clear: both;"></div>';
      html += '<div class=" blockCol3 smallTxt">' + item.Class + '&nbsp;|&nbsp;' + item.Trip + '</div><br><div style="clear: both;"></div>';
      html += '<div class="btnHolder"><input name="button" class="btn-finder" type="button" data-item="' + encodeURIComponent(JSON.stringify(item)) + '" class="searchBtn wth150" href="#" value="Book now" /></div></div>';
    });
    $("#dvPromotion").empty();
    $("#dvPromotion").html(html);
  }
});

// Attach an event listener to the document element (or any other parent element of your buttons)
$(document).on('click', '.btn-finder', function() {
  console.dir(JSON.parse(decodeURIComponent($(this).data('item'))));
});

You can create a div (or any DOM object) object with jQuery and assign properties to it. 您可以使用jQuery创建div(或任何DOM对象)对象并为其分配属性。 For an example: 举个例子:

// Create an image tag with appropriate properties
var img = jQuery('<img/>', {
    src: '/PublishingImages/'
});

// Create a div tag with appropriate properties
var div = jQuery('<div/>', {
    class: 'tileBlock'
});

// Append the image tag in the div
div.append(img);

This way is a little bit better (because it improves the readability) than the string concatenation you implemented. 这种方式比您实现的字符串连接更好(因为它提高了可读性)。

However I suggest you to use a template engine (for example Mustache.js ) if you're searching for a long-term solution and better architecture. 但是,如果您正在寻找长期解决方案和更好的架构,我建议您使用模板引擎(例如Mustache.js )。

One of the best ways to do templating in the native JavaScript, tried in a large scale project. 在大型项目中尝试在本机JavaScript中进行模板化的最佳方法之一。 A very small piece is here for POC. 对于POC来说,这是一个非常小的部分。

function(cellValue, options, rowObject) {
                        var markup = "<a title=\"%ToolTip%\" href=%Href%;>%Text%</a>";
                        var replacements = {
                            "%Text%": rowObject.EmployeeName,
                            "%ToolTip%": Employee.messages && Employee.messages.ClickHereToEdit
                                ? Employee.messages.ClickHereToEdit : "",
                            "%Href%": "javascript:Employee.openAddEditModal(&apos;" + rowObject.EmployeeId + "&apos;)"
                        };
                        markup = markup.replace(/%\w+%/g, function(all) {
                            return replacements[all];
                        });
                        return markup;
                    }

I usually, for this kind of work, create an hidden template in my html, and then use it. 我通常,为了这种工作,在我的html中创建一个隐藏的模板,然后使用它。

Then for every item i need to place in my html, i clone the template and insert in the place i want it. 然后对于我需要放在我的html中的每个项目,我克隆模板并插入我想要的地方。

I show you how would i do it usually. 我告诉你我将如何做到这一点。

edit You can also bind the click on each item when you insert it. 编辑您也可以在插入每个项目时绑定点击。

Look at the .click associated to html.find('.btn-finder') 查看与html.find('.btn-finder')相关联的html.find('.btn-finder')

 var $template = $(".tileBlockTemplate"); $.ajax({ url: 'https://api.myjson.com/bins/1mkxw', method: "GET", headers: { "Accept": "application/json; odata=verbose" }, async: false, success: function(data) { $("#dvPromotion").empty(); $.each(data.results, function(i, item) { var html = $template.clone(); html.removeClass('tileBlockTemplate'); html.find('.tileImage').attr('src', '/PublishingImages/' + item.Title) .attr('alt', item.To.Title); html.find('.greyLabel').html(item.To.Title); html.find('.fareTxt').html(item.Cost + '&nbsp;' + item.From.Currency); html.find('.smallTxt').html(item.Class + '&nbsp;|&nbsp;' + item.Trip); html.find('.btn-finder').data('item', encodeURIComponent(JSON.stringify(item))) .click(function() { console.dir(JSON.parse(decodeURIComponent($(this).data('item')))); }); $("#dvPromotion").append(html); }); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="dvPromotion"> </div> <div style='display:none'> <div class="tileBlockTemplate tileBlock"> <img class="tileImage" src="/PublishingImages/abuDhabi.jpg" alt="Abu Dhabi"> <br> <div class="blockCol1 greyLabel">Abu Dhabi</div> <div class="blockCol2 fareTxt">60&nbsp;KWD</div> <div style="clear: both;"></div> <div class=" blockCol3 smallTxt">economy&nbsp;|&nbsp;RT</div> <br> <div style="clear: both;"></div> <div class="btnHolder"> <input name="button" class="btn-finder" type="button" data-item="" href="#" value="Book now"> </div> </div> </div> 

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

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