jQuery: Executing code for each element that matches a selector
$("p")
references all paragraphs on the current web page. Is i开发者_运维问答t possible to execute code for each element that matched the selector?
Here's a simplistic example in pseudo-code:
// Show the background color of every paragraph on the page
foreach (object = $("p")) {
alert(object.css("background-color"));
}
$('p').css('background-color', 'black')
If you need more flexibility:
$('p').each(function() {
$(this).css('background-color', 'red');
});
You can use .each()
for iterating through the matched elements, like this:
$("p").each(function() {
alert($(this).css("background-color"));
});
If you want to set or do something (e.g. not getting a value from each like above), there's no need for .each()
, just execute it and it'll run for every element on the set...this is the default jQuery behavior, for example:
$("p").show(); //shows all <p> elements
The each
method sounds like what you want
$('p').each(function() {
alert($(this).css('backgroundColor'));
}
精彩评论