如何选择一个包含变量的选择器? (Javascript,jQuery,DOM)

时间:2017-08-19 12:51:52

标签: javascript jquery twitter-bootstrap dom

我已经苦苦挣扎了几天,我有一个函数,它接受一个对象并循环通过它创建带有显示列的行(bootstrap),所以我使用jQuery来选择一个带有值的id从对象本身并附加到它,但由于某种原因,没有看到包含该变量的id选择器,并且不会附加到具有id的div?

function add_to_page(product) {
 //this is the main row that will contain the columns
 var rows = $('<div class="row" ></div>'); 
 for (var category in products) {
    for (var i = 0; i < products[category].length; i++) {
      rows.append($("<div id='" +products[category][i].id +"'></div>").html($('<img>').attr('src', products[category][i].img)));
      //the below code is never executed it only creates the image and stops appending after that
      $('#' + products[category][i].id).append($('<div class=name>').text(products[category][i].name));
      $('#' + products[category][i].id).append($('<div class=category>').text(products[category][i].category));
      $('#' + products[category][i].id).append($('<div class=price>').text('Price: ' + products[category][i].price + 'L.E'));
      $('#' + products[category][i].id).addClass('col-md-3');
      //the below code is to create a new row after filling each row with 4 display columns 
      if ( i % 3 == 0 && i != 0 ) {
        $('#content').append(rows.clone(true));
        rows = $('<div class="row"></div>');
      }
    }
  }
}

这是我想附加的html:

<div class="container full-width">
  <div id="content"></div>
</div>

我正常调用该函数,控制台中没有错误

add_to_page(products);

4 个答案:

答案 0 :(得分:2)

您不能使用选择器来查找尚未添加到文档中的元素(除非您使用$(selector, context)的第二个参数)。但是出于您的目的,您可以使用append方法可以接受多个参数的事实。

通过一些其他更改使您的代码更像jQuery,您可以得到:

&#13;
&#13;
function add_to_page(products) {
    //this is the main row that will contain the columns
    var rows = $('<div>').addClass("row"); 
    for (var category in products) {
        for (var item of products[category]) {
            rows.append(
                $("<div>").attr("id", item.id).addClass('col-md-3').append(
                    $('<img>').attr('src', item.img),
                    $('<div>').addClass('name').text(item.name),
                    $('<div>').addClass('category').text(item.category),
                    $('<div>').addClass('price').text('Price: ' + item.price + 'L.E')
                )
            );
            //the below code is to create a new row after filling each row with 3 display columns 
            if ( rows.children().length >= 3 ) {
                $('#content').append(rows);
                rows = $('<div>').addClass("row"); 
            }
        }
    }
    // Flush any rows that were not yet added:
    if ( rows.children().length ) {
        $('#content').append(rows);
    }
}

// Sample data
var products = {
    fruit: [{
        name: 'apple',
        price: 2.20,
        img: "https://www.colourbox.com/preview/7011130-apples-on-table-and-knife.jpg",
        category: 'fruit'
    }, {
        name: 'kiwi',
        price: 3.10,
        img: "https://www.colourbox.com/preview/10157893-kiwi-fruit.jpg",
        category: 'fruit'
    }, {
        name: 'banana',
        price: 1.50,
        img: "https://www.colourbox.com/preview/6294218-banana.jpg",
        category: 'fruit'
    }],
    vegetables: [{
        name: 'lettuce',
        price: 0.90,
        img: "https://www.colourbox.com/preview/2347661-fresh-salad-leaves-assortment-in-a-basket.jpg",
        category: 'vegetables'
    }, {
        name: 'radish',
        price: 1.60,
        img: "https://www.colourbox.com/preview/3602479-red-radish.jpg",
        category: 'vegetables'
    }]
};

add_to_page(products);
&#13;
.col-md-3 { display: inline-block; margin: 5px }
img { max-width: 100px }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container full-width">
  <div id="content"></div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

将所有动态html附加到存储在变量中的元素,然后将该变量附加到DOM。那个选择器不会工作bc你试图访问的元素还没有存在。

做类似的事情:

var el = $('<div' + id + '></div>')
el.append(your row constructed html)

然后将它附加到第二个for循环结束时的行。

修改

for(.... row iteration code) {
  var el = $('<div' + id + '></div>');
  el.append('your image goes here');
  el.append('name element');
  ...
  rows.append(el);
}

答案 2 :(得分:1)

使用@trincot's superior answer,但请注意,您也可以将整个HTML字符串传递给jQuery的.html()。 E.G:

function add_to_page(products) { 
  var $content = $("#content"), 
      cols=3, //number of columns
      $row, 
      i=0;
 
 for (var category in products) {
    for (var item of products[category]) {
      if(i%cols == 0){//add a new row
        $row = $("<div class='row'></div>");
        $content.append($row);
      }
      //add the item to the row
      $row.append($("<div class='col-md-"+cols+"' id='" +item.id +"'><img src='"+item.img+"' /><div class=name>"+item.name+"</div><div class=category>"+item.category+"</div><div class=price>Price: "+item.price+"L.E</div>"));
      i++;
    }
  }
}


var products = {
  "jam" : [
          {"id":1,"name":"strawberry", "category":"jam", "price":123, "img":"pic.gif"},
          {"id":2,"name":"rasberry", "category":"jam", "price":456, "img":"pic.gif"},
          {"id":3,"name":"madberry", "category":"jam", "price":123, "img":"pic.gif"},
          {"id":4,"name":"sadberry", "category":"jam", "price":456, "img":"pic.gif"}
          ],
  "bees" : [
          {"id":4,"name":"baz", "category":"bee", "price":1, "img":"pic.gif"},
          {"id":5,"name":"buzz", "category":"bee", "price":2, "img":"pic.gif"}
          ]
  };
  
//console.log(products);
add_to_page(products);
.row {display:block; border:1px solid blue;}
.row div[id] {display:inline-block; border:1px solid red; width:100px; margin:5px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container full-width">
  <div id="content"></div>
</div>

答案 3 :(得分:0)

您需要重新构建代码..您是否能够首先找到该元素  rows.append($( “”) 而是使用products.category [i] .id然后使用jQuery wrap()将列包装到行。