简体   繁体   中英

How do I register an event for a button in JavaScript?

I am making an HTML document for a javascript file. I want to use a button that will show the drawn rectangle, but I am still don't know fully on how would I code it. This is what my code looks like in HTML document. Also, when I open the html doc in FireFox, it does not show anything beside the title:

<!DOCTYPE html>
<!--Create a document that displays a drawn rectangle -->

<html lang = "en">

<head>
    <title> myRectangle.html </title>
    <meta charset = "utf-8" />
    <script type = "text/javascript" src = "myRects.js"
    </script>
</head>

<body>

<h3>Drawing Rectangle</h3>



<form id ="myCanvas" action = "">

<p>

<button> type ="button">Draw Me</button>

</p>

</form>


</body>

</html> 

This is what the JavaScript file looks like:

// myRects.js
// This script shows the use of the rectangle methods of the canvas
// element to draw two rectanges

function draw() {
    var dom = document.getElementById("myCanvas");
    if (dom.getContext) {
         var context = dom.getContext('2d');

     // Draw the outer filled rectangle
        context.fillRect(100, 100, 200, 200);

    // Clear a rectangle inside the first rectangle
        context.clearRect(150, 150, 100, 100);

    //Draw a stroke rectange
        context.strokeRect(180, 180, 40, 40);

    //Draw a small filled rectangle
        context.fillRect(195, 195, 10, 10);
    }
}

The reason only the title is shown is because you are missing a > after the opening tag of the script in the head: it should be like this:

<script type = "text/javascript" src = "myRects.js">
</script>

to run draw() when the button is clicked, do something like this:

<button id="click-to-draw"> Draw me </button>

And inside your script (you will need to move the location of the script tag to underneath the button)

document.getElementById("click-to-draw").addEventListener("click", function() {
draw();
});

Update : I just realized that you can simplify this to just document.getElementById("click-to-draw").addEventListener("click", draw);

Give your button an id:

<button type="button" id="draw-rectangle">Draw Me</button>

Add the following code to the end of your JavaScript file to hook the click event up to the draw() function:

document.getElementById("draw-rectangle").onclick = draw;

And fix your script tag in the head of the document:

<script type="text/javascript" src="myRects.js"></script>

如果你愿意,也可以使用onclick属性。

<button onclick='draw();'>Draw Me</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM