首页 > 解决方案 > Ajax 调用 - JS 不正确的表示法

问题描述

我们可以使用 each 方法来迭代 JavaScript 数组。

// To use the each() function, we first need to convert our JavaScript object into a jQuery object
// using the $() function.
// The function passed as a parameter to the each method is a "callback" and it specifies what to do
// with each element.
//
// Remember that a callback is a function passed into another function as an argument,
// which is then invoked inside the outer function to complete some kind of routine or action.

let url = 'https://google.com'
$.ajax(url).done(load);



function load(data) {
  console.log(data)
  $(document.body).append('<img>');
  $('img').attr('src', data.url)
  $('img').on('click', refresh)

}

function refresh() {
  $(this).remove();
  $.ajax(url).done(load);
}
$(people).each(function(index, value) {

  console.log("Exploring jQuery each method: ", index, value);

  let staffItem = $('<li>' + personToString(value) + '</li>');

  $('#directory').append(staffItem);


  staffItem.on("mouseover", highlightStaff)
    .on("mouseout", removeHighlight)
    .on("click", addStaff);


});


function highlightStaff() {
  $(this).addClass("hoverBackground");
}


function removeHighlight() {
  $(this).removeClass("hoverBackground");
}


function addStaff() {
  let selectedStaff = $(this).clone();
  selectedStaff.removeClass("hoverBackground");

  $("#selected-staff").append(selectedStaff);

  selectedStaff
    .on("mouseover", highlightStaff)
    .on("mouseout", removeHighlight)
    .on("click", removeStaff);
}

{
  $(this).remove();
}

标签: javascript

解决方案


推荐阅读