search

Home  >  Q&A  >  body text

Isn't rgb(255, 0, 0) 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(){
                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?


益伦益伦2637 days ago2094

reply all(2)I'll reply

  • 环海如星

    环海如星2017-10-10 19:06:35

    <!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!

    reply
    0
  • ringa_lee

    ringa_lee2017-10-09 09:27:08

    You need to traverse each

    reply
    0
  • 益伦

    I don’t understand. Can you explain it in more detail? I just learned it.

    益伦 · 2017-10-09 19:26:11
  • Cancelreply