Css格式泄漏到其他文档元素



正如标题所说,我是Web开发的新手,我尝试了JQuery,我遇到了这个问题。我在我的代码中指定id为#btn1的元素启用我写入它的特定特征,并且它只对id为#p1,#p2,#p3的元素这样做。为什么更改会泄漏到p的其他元素?

我希望这只格式化具有id (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>

因为这一行:

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

这一行为页面上的每个按钮添加了一个单击事件侦听器。所以当你点击任何按钮时,每一个& & "元素的背景色设置为黄色

最新更新