HTML中是否支持内联JavaScript事件子标记?

时间:2016-07-25 01:40:22

标签: javascript html

这里我们有一个带有onclick处理程序的div:

<div id="BorderContainer1282" onclick="alert('hello')">
    <input id="Button925" type="button" value="Button">
</div >

单击时会显示警告对话框。

HTML是否支持同名子标记中的内联JavaScript,如下所示:

<div id="BorderContainer1282">
    <onclick>alert('hello');</onclick>
    <input id="Button925" type="button" value="Button">
</div >

这个问题不是最佳做法。它特别关于HTML支持在HTML元素的子标记中设置事件,如示例中所示。

注意:我在示例2中测试了上面的代码,但它在我的测试中不起作用。

如果不起作用,请使用以下模板作为可接受的替代方案:

<div id="BorderContainer1282">
    <script type="text/javascript">
        document.getElementById('BorderContainer1282').addEventListener("click", function(event) {
            (function(event) {
                alert('hello');
            }).call(document.getElementById("BorderContainer1282"), event);
        });
    </script>
    <input id="Button925" type="button" value="Button">
</div >

同样,我现在并不关心最佳做法,只有支持此功能。

我发现了类似的问题here并非重复。

1 个答案:

答案 0 :(得分:0)

你的第二个例子是无效的HTML;没有<onclick>标记。您在第一个示例中执行JavaScript的原因是因为某些标记的Event attributes

这些属性允许您在给定元素上触发特定事件时执行任意JavaScript,虽然您不关心此处的最佳实践,但如果您希望保持标记清洁和有条理,则应避免使用它们。 / p>

您要查找的是第三个示例中的<script>标记,它允许在HTML标记的任何位置插入JavaScript,并且在这种情况下应该使用。您可以使用此标记和addEventListener将事件处理程序附加到div。这是在此方案中正确使用标记:

<div id="BorderContainer1282">
    <script type="text/javascript">
        document.getElementById("BorderContainer1282").addEventListener("click", function(e) {
            alert("Hello!");
        });
    </script>
    <input id="Button925" type="button" value="Button">
</div >

最后,<script>标记通常放在<body>的末尾,以确保在脚本执行之前已加载所有元素。您还可以通过将JavaScript包装在window.addEventListener("load", function(){ ... });

中来实现此目的
相关问题