javascript - 我是否使用了正确的函数让我的元素变红?

标签 javascript jquery css

好的,所以当使用 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/

相关文章:

jquery - 同一函数有多个 "user option"参数

css - 如何显示来自 Google 文档附加组件的 "Working"toast

html - 在 Bootstrap 中更改 div 顺序

javascript - 获取转换为 JSON 对象的问题

javascript - 如何在离开时将 slider 重置为幻灯片 1?

javascript - 从 native 数组中的对象获取键

javascript - 需要将多个复选框中的值拉入数组并将其存储为变量

javascript - 更改 jQuery UI 自动完成结果框样式

javascript - 文本框上的 Jquery 更改事件

javascript - 用 React 实现可排序表的正确方法是什么?