如何使用 javascript 在按钮中添加 onclick?

htmljavascriptfront end technology

onclick 事件通常在用户单击元素时发生。它使程序员能够在单击元素时运行 JavaScript 函数。此事件可用于验证表单、显示警告消息等。

可以使用 JavaScript 将此事件动态添加到任何元素。除了 <html>、<head>、<title>、<style>、<script>、<base>、<iframe>、<bdo>、<br>、<meta> 和 <param> 之外,它支持所有 HTML 元素。

在 HTML 中,我们可以使用 onclick 属性并将其与 JavaScript 函数关联。为了获得更大的灵活性,我们还可以使用 JavaScript 的 addEventListener() 方法并向其传递一个点击事件。

以下是在 HTML 中向元素添加 onclick 事件的语法。

<element onclick = "function()">

如果我们想在按钮中包含 onclick,我们必须将 onclick 事件属性添加到 <button> 元素。在本教程中,我们将介绍在 JavaScript 中执行按钮点击事件的两种不同方法。

object.onclick = function() { myScript };
object.addEventListener("click", myScript);

向 HTML 文档添加"onclick"事件

单击按钮时,onclick 事件会触发特定函数。这可能是当用户提交表单时、当我们更改网页上的某些内容时,或者当我们执行类似操作时。我们将要运行的 JavaScript 函数放在按钮的开始标记内。

示例

以下示例包含一个按钮和一个 JavaScript 函数,单击按钮时会显示一条隐藏消息。

<!DOCTYPE html>
<html>
  <head>
    <title>How to add onclick in a Button using JavaScript?</title>
    <style>
        button{
            background:lightgreen;
            color:darkolivegreen;
            font-weight:550;
        }
    </style>
  </head>
  <body>
    <p>Do you know the significance of Diwali? Click the button to know.</p>
    <button onclick="showmessage()">Click here</button>
    <p id="hiddentext"></p>
    <script>
      function showmessage() {
        document.getElementById("hiddentext").innerHTML = "In northern India, they celebrate the story of King Rama's return to Ayodhya after he defeated Ravana by lighting rows of clay lamps. Southern India celebrates it as the day that Lord Krishna defeated the demon Narakasura. Diwali symbolizes the victory of light over darkness and good over evil.";
      }
    </script>
  </body>
</html>

示例

在此示例中,我们将向几个按钮添加 onclick 属性,并编写 JavaScript 函数来更改字体的颜色和大小。

<!DOCTYPE html>
<html>
<head>
    <title>How to add onclick in a Button using JavaScript?</title>
    <style>
        body {
            background-color:azure;
            margin:20px;
        }
        p {
            font-size: 20px;
        }
        button {
            padding: 7px;
            border-radius: 10px;
            cursor: pointer;
        }
        button.blue {
            background-color: #3498db;
        }
    </style>
</head>
<body>
    <div>
        <p id="name">Sample Text</p>
        <button onclick="changeColor()">Change text color to Blue</button>
        <button onclick="changeSize()">Increase text size</button>
        <button onclick="reset()">Reset</button>
    </div>
    <script>
        function changeColor() {
            document.getElementById("name").style.color = "blue";
        }
        function changeSize() {
            document.getElementById("name").style.fontSize = "60px";
        }
        function reset() {
            document.getElementById("name").style.color="black";
            document.getElementById("name").style.fontSize="20px";
        }
    </script>
</body>
</html>

使用"click"事件监听器

在此特定示例中,我们将使用"click"事件监听器来更改 <div> 元素的背景颜色和边框属性。由于按钮的开始标记中没有 JavaScript,因此我们必须在脚本中选择按钮以及 <div> 元素。

示例

<!DOCTYPE html>
<html>
<head>
    <title>How to add onclick in a Button using JavaScript?</title>
    <style>
        body {
            background-color:floralwhite;
            margin:20px;
        }
        p {
            font-size: 20px;
        }
        button {
            background-color:lightcyan;
            border:0;
            margin-right:10px;
            padding: 7px;
            border-radius: 10px;
            cursor: pointer;
        }
        div{
            width:500px;
            height:150px;
            padding:10px;
        }
    </style>
</head>
<body>
    <div class="name">
      <p>The background color and border properties of this element can be changed using the buttons given below.</p>
      <button class="btn1">Change Background Color</button>
      <button class="btn2">Add border</button>
    </div>
    <script>
       const name = document.querySelector(".name");
       const btn1 = document.querySelector(".btn1");
       const btn2 = document.querySelector(".btn2");
       btn1.addEventListener("click", changeColor);
       function changeColor() {
        name.style.backgroundColor = "lavender";
      }
      btn2.addEventListener("click", addBorder);
       function addBorder() {
        name.style.border = "2px solid indigo";
      }
    </script>
</body>
</html>

示例

在下面的例子中,我们使用'click'事件监听器和相应的JavaScript函数在点击提交按钮时显示一个警告框。

<!DOCTYPE html>
<html>
<head>
    <title>How to add onclick in a Button using JavaScript?</title>
    <style>
        div{
            background-color:thistle;
            width:200px;
            height:150px;
            padding:10px 15px 15px 20px;
            margin:100px;
        }
        button{
            background-color:mintcream;
            height:25px;
            width:60px;
            border:0;
        }
        input{
            margin-top:8px;
        }
    </style>
</head>
<body>
    <div>
      <form name="form1" action="/action_page.php" method="get">
        <label for="fname">First name:</label><br>
        <input type="text" class="fname" name="fname"><br>
        <label for="lname">Last name:</label><br>
        <input type="text" class="lname" name="lname"><br><br>
      </form>
      <button class="btn">Submit</button>
    </div>
    <script>
       const btn = document.querySelector(".btn");
       btn.addEventListener("click", acknowledgement);
       function acknowledgement() {
        var fn = document.forms["form1"]["fname"].value;
        var ln = document.forms["form1"]["lname"].value;
        if (fn == "") {
            alert("First Name required");
        return false;
        }
        else if (ln == "") {
            alert("Last Name required");
        return false;
        }
        else
        alert("The form has been submitted successfully!");
      }
    </script>
</body>
</html>

相关文章