开发者

Is onclick embedded JavaScript?

This may be a subjective question. If so please close it.

Does onclick count as embedded JavaScript?

Or is it just usually the method开发者_如何转开发 called that’s actually the JavaScript part?


I’m not sure what you’re asking, but I’ll have a go anyway.

The onclick attribute that you can add to HTML elements (i.e. <a onclick="">) is HTML. However, its value is JavaScript that gets run when the user clicks on the element. That JavaScript (along with the association between that JavaScript and the HTML element’s click event) is indeed embedded in the HTML page, meaning you have to change your HTML page to change the JavaScript (or remove the association).

To avoid embedding JavaScript into your HTML page, you can instead add a handler function to the onclick DOM property of an element via JavaScript:

  1. Add a JavaScript file to your page, via the <script src=""> tag.
  2. In that file, set some code to run on page load (or when the DOM is ready, which is a whole other topic in itself).
  3. Have that code add an onclick handler function to an HTML element.

E.g. if your HTML looked like this

<a id="needs_onclick">I need an onclick handler</a>

Then you could add an onclick handler to the link like this:

window.onload = function(){
    document.getElementById("needs_onclick").onclick = function(){
        alert("Clicked!");
    }
}

This approach would not be described as “embedded JavaScript”, as it uses the onclick DOM property, not the onclick attribute.


(...) functions called "Event Handlers." These are commands that work directly with existing HTML commands. They work so closely in fact, they work by being embedded right into the HTML command itself.

The source: http://www.htmlgoodies.com/beyond/javascript/article.php/3470771/Advanced-JavaScript-for-Web-Developers-onClick-and-onMouseOver.htm

From mighty Google. Took me about 15 seconds to find it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜