簡體   English   中英

如何使用jquery,json和自定義數據屬性在map方法內嵌套map方法

[英]How do you nest a map method inside a map method using jquery, json and custom data attributes

我正在構建一個Rails應用程序。 我正在使用數據屬性來獲取json。

  <% @image_urls.each_slice(5) do |row| %>
    <% row.each do |_, urls| %>
      <li class="square-image" data-urls=<%= urls.to_json %>>
        <span class="user-image"><%= image_tag(urls.sample) %></span>
      </li>
    <% end %>
  <% end %>

使用此json,我試圖通過遍歷json中的不同URL來每秒更新src屬性。 時間到了。 當我制作第一個地圖時,我成功獲取了URL。

但是,當我執行嵌套映射時,出現錯誤“未捕獲的TypeError:未定義不是函數”。 現在,我沒有更新src部分,因為我只是嘗試獲取其中的每個URL。

我嘗試過的事情:

  • 將映射更改為每個=不成功。
  • 播放$(url)和$(u)的語法。

     var time = setInterval(function(){updateImage()}, 1000); var square_urls = ($($(".square-image")[0]).data("urls")); function updateImage(){ square_urls.map(function(urls){ urls.map(function(u){ console.log(u); }); }); } 

如果我不做第二張地圖,我將成功獲取URL。

第二個映射給我錯誤:“未捕獲的TypeError:未定義不是函數。”

我重新思考了一下,首先要專注於更新一個圖像。 我相信我試圖一次做太多事情,需要進一步分解。 在updateImage函數中,我通過查找長度來更新一個正方形的圖像,對其進行隨機更新,然后在數組中調用隨機化的url。

在updateImage工作之后,我便集中精力更新所有圖像。 在updateAllImages函數中,我可以使用updateImage函數,而不必嵌套,因此會使我的代碼混亂。 注意,起初我因為沒有意識到jquery的每個方法都調用索引和值(與Ruby不同)而被淘汰,所以我必須確保為索引添加一個參數(在本例中為_)。

通過time函數調用updateAllImages函數,該函數每秒更新一次。

視圖

  <ul>
  <% @image_urls.each_slice(5) do |row| %>
    <% row.each do |_, urls| %>
      <li class="square-image" data-urls=<%= urls.to_json %>>
        <span class="user-image"><%= image_tag(urls.sample) %></span>
      </li>
    <% end %>
  <% end %>
  </ul>  

JQuery的

  var squares = $(".square-image");
  var time = setInterval(function(){updateAllImages(squares)}, 1000);

  function updateAllImages(squares) {
    $.each(squares, function(_, square) {
      updateImage(square);
    });
  }

  function updateImage(square) {
    var urls = $(square).data("urls");
    var urlCount = urls.length;
    var randomIndex = Math.floor(Math.random() * urlCount);
    var newUrl = urls[randomIndex];

    // the image currently lives in a span so that's why I
    // need to call children twice
    var image = $(square).children().children()[0];
    image.src = newUrl;
  }
});

我想這就是你要的:

var $squares = $(".square-image");
var urls = $squares.map(function(square) { return $(square).data("urls"); });

根據jQuery的文檔:

返回的數組將被展平為結果數組。

因此,假設data-urls有一個數組,那么就無需再進行其他工作來從所有圖像生成所有URL。

請注意,jQuery的map函數旨在用作選擇器。 它無意產生副作用。

// Use `each` when you want to *do* something instead of *select* something.
$.each(urls, function(url) { console.log(url); });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM