// Function to modify the text content of the paragraph
const changeText = () = >{
const p = document.querySelector('p');
p.textContent = "I changed because of an inline event handler.";
}
首次加载events.html,您会看到如下所示的页面:
但是,当您或其他用户单击按钮时,p标记的文本将从Try to change me更改为。我改变了,因为内联事件处理程序。
// Function to modify the text content of the paragraph
const changeText = () = >{
const p = document.querySelector('p');
p.textContent = "I changed because of an event handler property.";
}
// Add event handler as a property of the button element
const button = document.querySelector('button');
button.onclick = changeText;
// Function to modify the text content of the paragraph
const changeText = () = >{
const p = document.querySelector('p');
p.textContent = "I changed because of an event listener.";
}
// Listen for click event
const button = document.querySelector('button');
button.addEventListener('click', changeText);
const p = document.querySelector('p');
const button = document.querySelector('button');
const changeText = () = >{
p.textContent = "Will I change?";
}
const alertText = () = >{
alert('Will I alert?');
}
// Multiple listeners can be added to the same event and element
button.addEventListener('click', changeText);
button.addEventListener('click', alertText);
在本例中,这两个事件都将触发,一旦单击退出警告,就向用户提供一个警告和修改后的文本。
通常,将使用匿名函数而不是事件侦听器上的函数引用。匿名函数是没有命名的函数。
// An anonymous function on an event listener
button.addEventListener('click', () = >{
p.textContent = "Will I change?";
});
还可以使用removeEventListener()函数从元素中删除一个或所有事件。
// Remove alert function from button element
button.removeEventListener('click', alertText);