javascript - 添加事件监听器

标签 javascript addeventlistener

我遇到了事件添加事件监听器功能的问题,它不会给出错误,它只是不起作用我什至听了复制和粘贴其他代码的视频来工作并修改我的 html 以使用,但它添加了事件监听器我的代码在这里不起作用

<!DOCTYPE html>
<html>
<head><title>Main page of a simple website</title>
    <link rel="stylesheet" type="text/css" href="mstn.css"/>
    <link href='https://fonts.googleapis.com/css?family=Josefin+Slab:100'  rel='stylesheet' type='text/css'>

</head>
    <body>
        <header>
            <a href="https://www.google.com" target="_parent">click here to go to google</a>
            <a href="victimclient.rar" download="victimclient.rar">here</a>

        <p id="demo">testing testing testing </p>
        <p>testing testing testing</p>
        <h1>whats little g</h1>
        <script type="text/javascript" src="checkthisout.js">
            y = document.getElementById("input").addEventListener("click", myFunction);
        if(y){
            function myFunction() { 
                alert("hello world")
            }
        }

        </script>
        <input holder="password" value="replace here" id="input"/>



    </body>

最佳答案

<!DOCTYPE html>
<html>
<head><title>Main page of a simple website</title>
    <link rel="stylesheet" type="text/css" href="mstn.css"/>
    <link href='https://fonts.googleapis.com/css?family=Josefin+Slab:100'  rel='stylesheet' type='text/css'>

</head>
    <body onload="init()">
        <header>
            <a href="https://www.google.com" target="_parent">click here to go to google</a>
            <a href="victimclient.rar" download="victimclient.rar">here</a>

        <p id="demo">testing testing testing </p>
        <p>testing testing testing</p>
        <h1>whats little g</h1>
        
        <input holder="password" value="replace here" id="input"/>


        <script type="text/javascript">
            function init() {
                 document.getElementById("input").addEventListener("click", myFunction);
            }
          
            function myFunction() { 
                alert("hello world")
            }

        </script>
    </body>

这是解决方案。 在操作 DOM 之前,您必须等待 DOM 被加载。 此外,此 script 标记中不能有 src 属性。

关于javascript - 添加事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39877032/

相关文章:

javascript - 具有放大和缩小的 map 图像以及图像不同位置的标记

javascript - 是否可以托管在一个文档中编码的网站?

javascript - 我如何在其他函数中调用自调用的 javascript 函数?

javascript - 更新到 addEventListener 可能会导致函数的返回值不传播?

javascript - 如何使用 angular2 在按钮单击时获取 primeng 下拉列表的选定文本

javascript - 如何创建 JavaScript 乘法表?

javascript - 事件监听器中的匿名函数与在事件监听器中运行的匿名函数

Javascript mousemove 空事件处理程序泄漏内存?

javascript - 未捕获的类型错误 : Illegal invocation on addEventListener

javascript - HasMany - BelongsTo 与 RESTAdapter Ember.js