好的,所以我试图让我的标题(所有3个标题)在使用changeStuff函数单击“红色标题”按钮时将颜色变为红色,但它似乎无法正常运行。那么这是我应该使用的正确功能吗?
<title>Stanford Graduation</title>
<style type="text/css">
.redElements {
color: red;
}
</style>
</head>
<body>
<h1>Graduation</h1>
<p>Graduation is the culmination of four (or more years of hard work).</p>
<h2>Graduation Traditions</h2>
<p>Stanford Graduation has it's own amazing traditions.</p>
<h3>The Wacky Talk</h3>
<p>Stanford Seniors act and dress wacky as they enter the stadium.</p>
<h3 id="speakerHeading">Speakers</h3>
<p>Stanford graduation speakers always have Stanford ties.</p>
<div>
<input type="button" value="Red Headings" id="theRedButton" />
<input type="button" value="Fade Out Speaker" id="theSpeakersButton" />
</div>
<script>
"jquery-2.1.4.js"
</script>
<script>
function changeStuff() {
$("h").addClass("redElements");
}
$("theRedButton").bind("click", changeStuff);
</script>
</body>
答案 0 :(得分:2)
要将类添加到所有标题元素,请使用:
function changeStuff() {
$("h1, h2, h3").addClass("redElements");
}
$("#theRedButton").on("click", changeStuff);
编辑:这里是您需要的完整HTML内容,其中还展示了如何引入jQuery并挂钩文档就绪回调:
<head>
<title>Stanford Graduation</title>
<style type="text/css">
.redElements {
color: red;
}
</style>
</head>
<body>
<h1>Graduation</h1>
<p>Graduation is the culmination of four (or more years of hard work).</p>
<h2>Graduation Traditions</h2>
<p>Stanford Graduation has it's own amazing traditions.</p>
<h3>The Wacky Talk</h3>
<p>Stanford Seniors act and dress wacky as they enter the stadium.</p>
<h3 id="speakerHeading">Speakers</h3>
<p>Stanford graduation speakers always have Stanford ties.</p>
<div>
<input type="button" value="Red Headings" id="theRedButton" />
<input type="button" value="Fade Out Speaker" id="theSpeakersButton" />
</div>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function() {
$("#theRedButton").on("click", changeStuff);
});
function changeStuff() {
$("h1, h2, h3").addClass("redElements");
}
</script>
</body>
这是一支正在使用它的工作笔:http://codepen.io/Ghazgkull/pen/rVRRbK
答案 1 :(得分:1)
试试这个
$("h1,h2,h3").addClass("redElements");
没有元素名称h
对于id jquery使用#
。
没有#
jquery处理提供的选择器作为元素
像这样添加
$("#theRedButton").bind("click",changeStuff);
答案 2 :(得分:1)
您的代码存在语法错误。
将其更改为
function changeStuff() {
$("h1,h2,h3").addClass("redElements");
}
$("#theRedButton").bind("click", changeStuff);
https://jsfiddle.net/2oj1s9mg/
另外
<script>
"jquery-2.1.4.js"
</script>
应该是
<script src="jquery-2.1.4.js"></script>
答案 3 :(得分:0)
$("#theRedButton").bind("click",changeStuff);
为id
添加了一个#且$('h')
应该是$('h1,h2,h3,h4,h5');
//或者您希望在页面上获得该类的任何内容
另外我可以看到jquery我希望你试图演示一个伪代码,否则你必须包含jQuery