map

« Обратно к списку traversing-функций

map( вызов )

Преобразует набор элементов в объекте jQuery в другой набор значений в виде массива jQuery (который может содержать или не содержать элементы).
Данным методом можно пользоваться для составления списков значений, атрибутов, значений css или даже создавать пользовательский специальный селектор.
Аргументы:

вызов Функция
Функция, исполняемая для каждого элемента в наборе.

function callback(index, domElement) {
  var replacement;

  this; // also dom element

  // replacement == null : delete spot
  // replacement == array : insert the elements of the array
  // else replace the spot with replacement
  return replacement;
}
Примеры:

Построение списка всех значений элементов в пределах формы.
    $("p").append( $("input").map(function(){
      return $(this).val();
    }).get().join(", ") );
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>

  <script>

  $(document).ready(function(){

    $("p").append( $("input").map(function(){
      return $(this).val();
    }).get().join(", ") );

  });
  </script>

  <style>
  p { color:red; }
  </style>
</head>
<body>
  <p><b>Values: </b></p>

  <form>
    <input type="text" name="name" value="John"/>
    <input type="text" name="password" value="password"/>

    <input type="text" name="url" value="http://ejohn.org/"/>
  </form>
</body>
</html>
Искусственный пример, показывающий некоторые функциональные возможности.
    var mappedItems = $("li").map(function (index) {
      var replacement = $("<li>").text($(this).text()).get(0);
      if (index == 0) {
        // make the first item all caps
        $(replacement).text($(replacement).text().toUpperCase());
      } else if (index == 1 || index == 3) {
        // delete the second and fourth items
        replacement = null;
      } else if (index == 2) {
        // make two of the third item and add some text
        replacement = [replacement,$("<li>").get(0)];
        $(replacement[0]).append("<b> - A</b>");
        $(replacement[1]).append("Extra <b> - B</b>");
      }

      // replacement will be an dom element, null,
      // or an array of dom elements
      return replacement;
    });
    $("#results").append(mappedItems);
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>

  <script>
  $(document).ready(function(){

    var mappedItems = $("li").map(function (index) {
      var replacement = $("<li>").text($(this).text()).get(0);
      if (index == 0) {
        // make the first item all caps
        $(replacement).text($(replacement).text().toUpperCase());
      } else if (index == 1 || index == 3) {
        // delete the second and fourth items
        replacement = null;
      } else if (index == 2) {
        // make two of the third item and add some text
        replacement = [replacement,$("<li>").get(0)];
        $(replacement[0]).append("<b> - A</b>");
        $(replacement[1]).append("Extra <b> - B</b>");
      }

      // replacement will be an dom element, null,
      // or an array of dom elements
      return replacement;
    });
    $("#results").append(mappedItems);

  });
  </script>

  <style>
  body { font-size:16px; }
  ul { float:left; margin:0 30px; color:blue; }
  #results { color:red; }
  </style>
</head>
<body>
  <ul>
    <li>First</li>

    <li>Second</li>
    <li>Third</li>
    <li>Fourth</li>
    <li>Fifth</li>

  </ul>
  <ul id="results">
  </ul>
</body>
</html>
Name Type