【问题标题】:Looping over items in array to assign data-id, but only getting last item in array循环遍历数组中的项目以分配数据ID,但仅获取数组中的最后一项
【发布时间】:2017-03-27 15:17:04
【问题描述】:

目标

  • 给每个礼物一个data-id,一直到gifts.length(即245),这将帮助我从数组中提取相应的数据
  • 找到一种更好的方法来为数组中的所有礼物重复结构 .gift 结构

问题

我有一个包含 200 多个礼物的数组,它们都具有相似的结构,我一直在尝试为每个礼物赋予一个唯一的数据 ID,但我得到了数组中的最后一个 ID,这是 245

我还想知道在不必使用 handlebars.js 之类的情况下重复此结构的最佳方法是什么,我尝试过 multiplyNode,但我不确定浏览器支持与 @987654326 相比是否更好@

    <div class="gift data-id="">
        <img src="" data-original="" class="gift__image lazy">
        <p class="gift__name">tk-name</p>
        <p class="gift__price">tk-price</p>

        <p class=""><span class="gift__description">tk-description</span> <a href="" class="gift__link">tk-url</a></p>

        <div class="gift__share">
            <div class="gift__icons">
                <a href="" class="link--twitter" target="_blank"><i class="fa fa-twitter" aria-hidden="true"></i></a>
                <a href="" class="link--facebook" target="_blank"><i class="fa fa-facebook" aria-hidden="true"></i></a>
                <a href="" class="link--pinterest" target="_blank"><i class="fa fa-pinterest-p" aria-hidden="true"></i></a>
                <a href="" target="_blank"><i class="fa fa-envelope" aria-hidden="true"></i></a>
            </div>
        </div>
        <a href="" target="_blank"><button class="btn btn--buy">Buy on Amazon</button></a>
    </div> <!-- .gift -->

scripts.js

// Loop over all of the gifts
for (let i = 0; i < gifts.length; i++) {

    $(".gift").attr("data-id", [i]);

    // Gift information from gifts.js
    let giftName = $(".gift__name").html(gifts[i].Name);
    let giftPrice = $(".gift__price").html(gifts[i].Price).prepend("$");
    let giftDescription = $(".gift__description").html(gifts[i].Description);
    let giftLink = $(".gift__link").html(gifts[i].URL);
}

function multiplyNode(node, count, deep) {
    for (var i = 0, copy; i < count - 1; i++) {
        copy = node.cloneNode(deep);
        node.parentNode.insertBefore(copy, node);
    }
}

const totalGifts = gifts.length
multiplyNode(document.querySelector('.gift'), totalGifts, true);

gifts.js(共有245个礼物)

var gifts = [
  {
    "ID": 1,
    "Name": "Air plants",
    "Price": 25,
    "Description": "A small glass globe containing air plants, gravel, moss and crystals, comes in various designs and can brighten up your window or desk ($25) at Flowers and Weeds, 3201 Cherokee Street, flowersandweeds.com, which also sells monthly subscription boxes at various price points.",
    "Category": "Gifts for anyone",
    "Type": "Other",
    "URL": "flowersandweeds.com",
    "Destination": "Cherokee Street",
    "Location": "Flowers and Weeds, 3201 Cherokee Street",
    "Latitude": 38.59,
    "Longitude": -90.2369742,
    "Position": "38.5949207, -90.2369742",
    "ImageURL": "-"
  }
];

【问题讨论】:

  • 我在使用 let 时遇到了一些奇怪的问题。您是否尝试过 var 代替?还有 $(".gift").attr("data-id", [i]);我认为您可以删除 i 周围的 []。而是像这样--> $(".gift").attr("data-id", i);
  • 也许$($(".gift")[i]).attr("data-id", i);
  • @Icewine (".gift").attr("data-id", i) 不幸的是一遍又一遍地产生相同的data-id
  • @vothaison 尝试了你的推荐,它产生了一个空 id
  • console.log(gifts.length)

标签: javascript jquery arrays node.js for-loop


【解决方案1】:

在我看来,您每次通过循环时都会将每个 id 分配(并替换它)给具有 .gift 类的所有元素。 尝试仅将其分配给当前的礼物:

var gift = $($(".gift")[i]);
gift.attr("data-id", [i]); 

【讨论】:

  • 试过你的sn-p,它显然给每件礼物一个0的数据ID
【解决方案2】:

这可能不是你想要的方式,但如果我这样做,我会这样做:

var gifts = [{
  "ID": 1,
  "Name": "1 Air plants",
  "Price": 400,
  "Description": "A small glass globe containing air plants, gravel, moss and crystals, comes in various designs and can brighten up your window or desk ($25) at Flowers and Weeds, 3201 Cherokee Street, flowersandweeds.com, which also sells monthly subscription boxes at various price points.",
  "Category": "Gifts for anyone",
  "Type": "Other",
  "URL": "flowersandweeds.com",
  "Destination": "Cherokee Street",
  "Location": "Flowers and Weeds, 3201 Cherokee Street",
  "Latitude": 38.59,
  "Longitude": -90.2369742,
  "Position": "38.5949207, -90.2369742",
  "ImageURL": "-"
}, {
  "ID": 2,
  "Name": "2 Dandilions",
  "Price": 12,
  "Description": "Some explaination here.....",
  "Category": "Gifts for anyone",
  "Type": "Other",
  "URL": "flowersandweeds.com",
  "Destination": "Cherokee Street",
  "Location": "Flowers and Weeds, 3201 Cherokee Street",
  "Latitude": 38.59,
  "Longitude": -90.2369742,
  "Position": "38.5949207, -90.2369742",
  "ImageURL": "-"
}, {
  "ID": 3,
  "Name": "3 Air plants",
  "Price": 6662,
  "Description": "A small glass globe containing air plants, gravel, moss and crystals, comes in various designs and can brighten up your window or desk ($25) at Flowers and Weeds, 3201 Cherokee Street, flowersandweeds.com, which also sells monthly subscription boxes at various price points.",
  "Category": "Gifts for anyone",
  "Type": "Other",
  "URL": "flowersandweeds.com",
  "Destination": "Cherokee Street",
  "Location": "Flowers and Weeds, 3201 Cherokee Street",
  "Latitude": 38.59,
  "Longitude": -90.2369742,
  "Position": "38.5949207, -90.2369742",
  "ImageURL": "-"
}, {
  "ID": 4,
  "Name": "4 Air plants",
  "Price": 2325,
  "Description": "A small glass globe containing air plants, gravel, moss and crystals, comes in various designs and can brighten up your window or desk ($25) at Flowers and Weeds, 3201 Cherokee Street, flowersandweeds.com, which also sells monthly subscription boxes at various price points.",
  "Category": "Gifts for anyone",
  "Type": "Other",
  "URL": "flowersandweeds.com",
  "Destination": "Cherokee Street",
  "Location": "Flowers and Weeds, 3201 Cherokee Street",
  "Latitude": 38.59,
  "Longitude": -90.2369742,
  "Position": "38.5949207, -90.2369742",
  "ImageURL": "-"
}];



// Loop over all of the gifts
for (var i = 0; i < gifts.length; i++) {

  // Gift information from gifts.js
  // -------------------------------------------------------------
  // This is how I would do it. This way is really easy to set up.
  // ------------------------------------------------------------
  var id = i;
  var giftName = gifts[i].Name;
  var giftPrice = "$" + gifts[i].Price;
  var giftDescription = gifts[i].Description;
  var giftLink = gifts[i].URL;

  var dataBlock = "<div class='gift' data-id='" + i + "'>\
					<img src='' data-original='' class='gift__image lazy'>\
					<p class='gift__name'>" + giftName + "</p>\
					<p class='gift__price'>" + giftPrice + "</p>\
					<p class=''><span class='gift__description'>" + giftDescription + "</span> <a href='' class='gift__link'>" + giftLink + "</a>\
					</p>\
					<div class='gift__share'>\
						<div class='gift__icons'>\
							<a href='#' class='link--twitter' target='_blank'>\
								<i class='fa fa-twitter' aria-hidden='true'></i>\
							</a>\
							<a href='#' class='link--facebook' target='_blank'>\
								<i class='fa fa-facebook' aria-hidden='true'></i>\
							</a>\
							<a href='#' class='link--pinterest' target='_blank'>\
								<i class='fa fa-pinterest-p' aria-hidden='true'></i>\
							</a>\
							<a href='#' target='_blank'>\
								<i class='fa fa-envelope' aria-hidden='true'></i>\
							</a>\
						</div>\
					</div>\
					<a href='#' target='_blank'>\
						<button class='btn btn--buy'>Buy on Amazon</button>\
					</a>\
				</div>";

  // ---------------------------------------------------
  // append to the contents
  // ---------------------------------------------------
  $("#contents").append(dataBlock);
}
.gift {
  background: #22252b;
  padding: 20px;
  margin-bottom: 10px;
  color: #FFF;
}
.gift__link {
  text-decoration: none;
  color: deepskyblue;
}
.gift__icons i {
  font-size: 20px;
  margin: 5px;
}
.gift__icons a {
  text-decoration: none;
  color: #FFF;
  float: right;
}
.gift__icons a:hover {
  opacity: 0.7;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://use.fontawesome.com/b64737b88c.js"></script>


<div id="contents"></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    • 2014-08-19
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    相关资源
    最近更新 更多