JavaScript作为HTML属性是不好的做法吗? [英] Is JavaScript as HTML Attribute Bad Practice?

查看:89
本文介绍了JavaScript作为HTML属性是不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例: https://stackoverflow.com/a/372​​89566/710887

我看到这种情况越来越频繁.

我总是被教导要使javascript,css和html分开(通过html链接到源代码/脚本).

是在HTML属性(例如onclick, onchange, etc:)中使用Javascript吗?

 <span id="valBox">25</span>
<input type="range" min="5" max="50" step="1" value="25" onchange="valBox.textContent = this.value"> 

解决方案

从本质上讲,这不是错误,但是,是的,大多数人都认为这是错误的做法.

优良作法是尽可能地将HTML和Javascript分开.它与CSS的概念相同.将HTML,CSS和Javascript混合在同一个文件中会很快变得难以管理,如果可能的话,应避免使用它.

理想情况下,这两个文件应该位于单独的文件中(.html.js文件),但是在HTML中将它们分开是一个很好的第一步.

您可以使用事件侦听器将两者分开,如下所示:

<!-- The elements -->
<span id="valBox">25</span>
<input id="inputBox" type="range" min="5" max="50" step="1" value="25">

<script>
    // Grab the elements here
    var val = document.getElementById("valBox");
    var inp = document.getElementById("inputBox");

    // Add an event listener to the input element and
    // set the span value when it changes
    inp.addEventListener("change", function () {
        val.textContent = this.value;
    });
</script>

如果您需要支持IE< = 9,请参见此答案.

Example: https://stackoverflow.com/a/37289566/710887

I see this happening more and more often.

I was always taught to keep javascript, css, and html separate (with html linking to the sources/scripts of course).

Is using an Javascript in an HTML attribute (such as onclick, onchange, etc:) bad practice?

<span id="valBox">25</span>
<input type="range" min="5" max="50" step="1" value="25" onchange="valBox.textContent = this.value">

解决方案

It is not wrong, per se, but yes, it is seen as bad practice by the vast majority of people.

Good practice is to separate the HTML and Javascript as much as you can. It is the same concept as with CSS. Mixing up the HTML, CSS and Javascript in the same file can become unmanageable very quickly, and should be avoided, if at all possible.

Ideally, the two should be in separate files (.html and .js files), but separating them in the HTML is a good first step.

You can separate the two by using event listeners, like so:

<!-- The elements -->
<span id="valBox">25</span>
<input id="inputBox" type="range" min="5" max="50" step="1" value="25">

<script>
    // Grab the elements here
    var val = document.getElementById("valBox");
    var inp = document.getElementById("inputBox");

    // Add an event listener to the input element and
    // set the span value when it changes
    inp.addEventListener("change", function () {
        val.textContent = this.value;
    });
</script>

See this answer if you need to support IE<=9.

这篇关于JavaScript作为HTML属性是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆