<script>
var ohnoesEl = document.getElementById("ohnoes");
var onOhNoesClick = function(e) {
e.preventDefault();
var audioEl = document.createElement("audio");
audioEl.src = "https://www.kasandbox.org/programming-sounds/rpg/giant-no.mp3";
audioEl.autoplay = "true";
document.body.appendChild(audioEl);
};
ohnoesEl.addEventListener("click", onOhNoesClick);
</script>
在这段代码中,我不明白一件事。我检查了互联网和StackOverflow,但找不到任何东西。
我在理解事件属性时遇到问题。
为什么我们在使用诸如preventDefault
之类的属性之前将e作为参数?
我将如何意识到我是否应该使用它?
我在理解事件属性时遇到问题。
好吧,这不是一个财产。所有事件处理函数都会自动传递对表示当前正在处理的事件的event
对象的引用。这个对象可以告诉你很多关于事件发生时的情况(即点击了哪个鼠标按钮,按下了什么键,点击发生时鼠标在屏幕上的位置,什么对象触发了事件等)。
为什么我们在使用诸如 防止违约?
e.preventDefault()
的语法只是常见的面向对象编程语法:Object.method()
。我们正在访问使用e
标识符传入函数的Event
对象,然后调用存储在该对象中的preventDefault
方法。
这就是您获得某些特定于对象的行为的方式。.preventDefault()
不是全局函数,但不能单独调用它。这只是event
对象可以执行的操作,因此必须在调用方法之前引用该对象。
与所有函数参数一样,您可以调用参数的任何有效名称,但由于对象将是事件对象,因此e
、evt
和event
很常见。
我将如何意识到我是否应该使用它?
在代码中:e.preventDefault()
,指示触发的事件不应执行其内置操作,从而有效地取消事件。
在用户已启动某个事件,但代码确定该过程不应继续的情况下,可以使用此技术。最好的示例是窗体的submit
事件。如果用户尚未填写所有必填字段,然后点击submit
按钮,则我们不希望提交表单,因此我们会检查是否填写了必填字段,如果没有,我们将取消submit
事件。
下面是一个示例:
// Get a reference to the link:
var link = document.getElementById("nasaLink");
// Set up a click event callback function that will automatically
// be passed a reference to the click event when it occurs. In this
// example, the event will be received as "evt".
link.addEventListener("click", function(evt){
console.clear(); // Cancel previous log entries
// Get the type of event that was received and the object that triggered it
console.log("You triggered a " + evt.type + " on :", evt.target)
// Cancelling an event is generally based on some condition
// Here, we'll make it simple and say that if you click on the
// link when the second is an even second, the navigation will be cancelled
if(new Date().getSeconds() % 2 === 0){
// Normally, clicking a valid hyperlink will navigate you away from the current page
// But, we'll cancel that native behavior by cancelling the event:
evt.preventDefault();
console.log(evt.type + " cancelled! No navigation will occur.");
}
console.log("The mouse was postioned at: " + evt.screenX + " x " + evt.screenY);
console.log("The SHIFT key was pressed at the time? " + evt.shiftKey);
console.log("tTry clicking again, but with SHIFT held down this time.");
});
<a href="http://www.nasa.gov" id="nasaLink" target="_blank">Click for NASA</a>
事件属性是传递给每个事件处理程序的对象。
然后,此事件对象具有许多属性和方法,您可以调用这些属性和方法来操作处理程序中的事件进程和操作。
例如,在事件对象中,您有一个名为preventDefault()
的方法。preventDefault()
做什么?每个事件都由页面中的特定 html dom 元素触发。有时这个 html 元素会附加行为。例如,<a>
元素有可能更改特定窗口的浏览器 URL。如果触发事件的元素是<a>
,则preventDefault()
您只需剪切该<a>
锚点的默认行为,这将避免 url 加载/更改。
我建议你找到这个event
对象的参考并阅读它。因此,您将更加熟悉其中可用的内容。