按钮点击= "handle_clicks()" ..handle_clicks没有定义,我可以在html element.onclick中使用(this)作为参数吗?



您能检查这段代码并找出为什么它不能正常工作吗?有两件事我想澄清……为什么函数没有定义?我能用(这个)吗?

HTML:

In head:
<script src="script.js"></script>
In body:
<button type="button" onclick="handle_clicks(this)">button1</button>
<button type="button" onclick="handle_clicks(this)">button2</button>

JS:

window.onload = () => {
function handle_clicks(btn) {
btn.style.background = 'green';
console.log('A button was clicked');
}
}

将脚本标签粘贴到正文末尾,并调用js函数,如:

<button type="button" onclick="handle_clicks(event)">button1</button>

现在在JS中使用简单的函数没有windows.onload

function handle_clicks($event) { // $ is used for events
const elm = $event.target
elm.style.background = 'green';
console.log('A button was clicked');
}

最新更新