18910140161

JavaScript-如何将此代码中HTML中的onclick()方法替换为JS中的替代方法?-堆栈溢出

顺晟科技

2022-10-18 13:40:57

154

我想用其他东西来改变HTML中按钮的onClick方法,以避免使用onClick.我在网上找到了AddEventListener,但不确定如何在这里替换?下面是我的代码:

function leapYear() {
    let input = document.getElementById("year");
    let year = parseInt(input.value);
    console.log(year);
    let output = document.getElementById("output");
    

    year = (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0);
    output.innerHTML = 'Year ' + year + '. is' + (year ? '' : ' not') + ' leap year.';

}
<代码><;!文档类型HTML>;<;HTML Lang=“ en ”>;<;头部>;<;元字符集=“ UTF-8 ”>;<;meta HTTP-equiv=“ X-ua-compatible ” content=“ ie=edge ”>;<;meta name=“ viewport ” content=“ width=device-width,initial-scale=1.0 ”>;<;标题>;文档<;/标题>;<;/标题>;<;身体>;<;H1>;闰年<;/H1>;<;P>;输入年份:<;/p>;<;细分(>;)<;输入ID=“年” type=“ text ” size=“ 24 ”/>;<;button onclick=“闰年()”>;检查闰年<;/button>;<;br/>;<;SPAN ID=“ output ”>;<;/SPAN>;<;/DIV>;<;script SRC=“ leap year.JS ”>;<;/script>;<;/正文>;<;/HTML>;


顺晟科技:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Leap Years</h1> <p>Type a year:</p> <div> <input id="year" type="text" size="24" /> <button onclick="leapYear()">Check leap year</button> <br /> <span id="output"></span> </div> <script src="LeapYear.js"></script> </body> </html>的第一个参数设置为addEventListener,将第二个参数设置为函数:

'click'
<代码><;!文档类型HTML>;<;HTML Lang=“ en ”>;<;头部>;<;元字符集=“ UTF-8 ”>;<;meta HTTP-equiv=“ X-ua-compatible ” content=“ ie=edge ”>;<;meta name=“ viewport ” content=“ width=device-width,initial-scale=1.0 ”>;<;标题>;文档<;/标题>;<;/标题>;<;身体>;<;H1>;闰年<;/H1>;<;P>;输入年份:<;/p>;<;细分(>;)<;输入ID=“年” type=“ text ” size=“ 24 ”/>;<;button>;检查闰年<;/button>;<;br/>;<;SPAN ID=“ output ”>;<;/SPAN>;<;/DIV>;<;script SRC=“ leap year.JS ”>;<;/script>;<;/正文>;<;/HTML>;

  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航