开发者

jQuery: Executing code for each element that matches a selector

开发者 https://www.devze.com 2023-01-08 07:05 出处:网络
$(\"p\") references all paragraphs on the current web page. Is i开发者_运维问答t possible to execute code for each element that matched the 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'));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消