<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ alert("背景颜色 = " + $("p").css("background-color")); }); }); </script> </head> <body> <h2>这是一个标题</h2> <p style="background-color:#ff0000">这是一个段落。</p> <p style="background-color:#00ff00">这是一个段落。</p> <p style="background-color:#0000ff">这是一个段落。</p> <button>返回 p 元素的 background-color </button> </body> </html>
Why is the returned result: background color = rgb(255, 0, 0)?
rgb(255, 0, 0) is not red. There are three p tags with different background colors. Why only the first red one is returned?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").each(function(i){
alert($(this).css("background-color"));
})
;body>
<h2>This is a title</h2>
<p style="background-color:#ff0000">This is a paragraph. </p>
<p style="background-color:#00ff00">This is a paragraph. </p>
<p style="background-color:#0000ff">This is a paragraph. </p>
<button>Returns the background-color of the p element </button>
</body>
</html>
should be written like this, because it will only take the first background-color of the value, and needs to loop through each!
You need to traverse each