我正在尝试获得更多JQuery实践。我有一个由标题和段落组成的HTML页面。当用户点击标题时,应放大下面的段落。此外,标题应将其背景颜色更改为#CCCCCC。最后,只有一个段落和标题应分别放大和着色。到目前为止,我已经尝试过:
09.js
$(document).ready(function(){
$('h2').click(function()
{
$(this).addClass('h2Color');
$(this).children('p').removeClass().addClass('large');
});
});
09.css
.h2Color{
background-color: #CCCCCC
}
.large {
font-size: 3.0em;
}
09.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Biography of Mark Twain</title>
<meta charset="utf-8">
<link rel="stylesheet" href="09.css" type="text/css" />
<script src="jquery.js"> </script>
<script src="09.js"> </script>
</head>
<body>
<h3>Title Of Page</h3>
<h1>Random H1 Element</h1>
<div>
<p>On then sake home is am leaf. Of suspicion do departure at extremely he believing. Do know said mind do rent they oh hope of. General enquire picture letters garrets on offices of no on. Say one hearing between excited evening all inhabit thought you. Style begin mr heard by in music tried do. To unreserved projection no introduced invitation.
</p>
</div>
<div>
<h2>Marilyn Monroe</h2>
<p>I have feelings too. I am still human. All I want is to be loved, for myself and for my talent.
</p>
<p>
I'm selfish, impatient, and a little insecure. I make mistakes, I'm out of control, and at times hard to handle. But if you can't handle me at my worst, then you sure don't deserve me at my best.
</p>
</div>
<div>
<h2>Richard Dawkins</h2>
<p>I am against religion because it teaches us to be satisfied with not understanding the world.
</p>
<p>Personally, I rather look forward to a computer program winning the world chess championship. Humanity needs a lesson in humility.
</p>
</div>
<div>
<h2 >John F. Kennedy</h2>
<p>
Let every nation know, whether it wishes us well or ill, that we shall pay any price, bear any burden, meet any hardship, support any friend, oppose any foe to assure the survival and the success of liberty.
</p>
</div>
</body>
</html>
我不知道为什么它不起作用。我想这只是我现在没有看到的东西。感谢
答案 0 :(得分:0)
$('h2').click(function () {
$(this).addClass('h2Color');
$(this).next('p').removeClass().addClass('large');
});
使用.next()
,因为您只想放大1个段落
如果您希望放大与h2
标记相关的所有参数,请使用此
$('h2').click(function () {
$(this).addClass('h2Color');
$(this).parent('div').find('p').removeClass().addClass('large');
});
$(this).children('p')
错误,因为h2
不能将段落作为其子句。
答案 1 :(得分:0)
段落不是h2代码的子代,但是siblings
你也没有删除大班。
$('h2').click(function()
{
$(this).addClass('h2Color');
$(this).siblings('p').addClass('large');
});
答案 2 :(得分:0)
h2
元素没有children()
,因此它不会影响任何元素。而是尝试:
$('h2').click(function() {
$(this).addClass('h2Color');
$(this).closest('div').find('p').removeClass().addClass('large');
});
虽然我建议使用toggleClass()
:
$('h2').click(function() {
$(this).addClass('h2Color');
$(this).closest('div').find('p').toggleClass('large');
});
或者,如果您希望一次只有一个'放大'部分,请首先从所有元素中删除large
类名,然后将其添加到仅点击元素:
$('h2').click(function () {
$('.large').removeClass('large');
$(this).addClass('h2Color').closest('div').find('p').addClass('large');
});