简体   繁体   English

JQuery Css Formatting 泄漏到其他文档元素

[英]JQuery Css Formatting leaks to other document elements

As the title says i am new to Web Development and i tried out JQuery and i came across this issue.正如标题所说,我是 Web 开发的新手,我尝试了 JQuery,但遇到了这个问题。 I am specifying on my code that the element with id #btn1 enables the specific characteristic i write it to and it does that only to elements with id #p1,#p2,#p3.我在我的代码中指定带有 id #btn1 的元素启用我写入它的特定特征,它只对带有 id #p1、#p2、#p3 的元素执行此操作。 Why do the changes leak to other elements of p?为什么更改会泄漏到 p 的其他元素?

I expected this to format only the elements with ids(p1,p2,p3) but it formats the other p elements too.我预计这只会格式化具有 ids(p1,p2,p3) 的元素,但它也会格式化其他 p 元素。

<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").css("background-color", "yellow");
  });

  $("#btn1").click(function(){
    $("#p1,#p2,#p3").css({"background-color": "yellow", "font-size": "200%"}); // 
  });
});
</script>
<body>

<h2>This is a heading</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>

<p>This is a paragraph.</p>

<button>Set background-color of p</button>

<br><hr><br>

<div id="div1">  

    <h2>This is a heading</h2>


<p id="p1" style="background-color:#ff0000">This is a paragraph.</p>
<p id="p2" style="background-color:#00ff00">This is a paragraph.</p>
<p id="p3" style="background-color:#0000ff">This is a paragraph.</p>

<p>This is a paragraph.</p>

<button id="btn1">Set multiple styles for p</button>

</div>

</body>

Its because of this line here:这是因为这里的这一行:

$("button").click(function(){
  $("p").css("background-color", "yellow");
});

This line adds a click event listener to every button on the page.此行向页面上的每个按钮添加一个点击事件侦听器。 So when you click any button, every "p" element on the page gets the background-color set to yellow因此,当您单击任何按钮时,页面上的每个“p”元素都会将背景颜色设置为黄色

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM