好的,所以当使用 changeStuff 函数单击“红色标题”按钮时,我试图让我的标题(所有 3 个标题)变成红色,但它似乎无法正常运行。那么这是我应该使用的正确功能吗?
<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>
最佳答案
要将类添加到所有标题元素,请使用:
function changeStuff() {
$("h1, h2, h3").addClass("redElements");
}
$("#theRedButton").on("click", changeStuff);
编辑:这是您需要的完整 HTML 内容,其中还显示了您应该如何引入 jQuery 并 Hook 到文档就绪回调中:
<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
关于javascript - 我是否使用了正确的函数让我的元素变红?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31932136/