我们可以使用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();
}