<!doctype html>
<html>
<body>
<img src="..." id="star">
<script>
star.onmousedown = function(event) {
alert()
};
</script>
</body>
</html>
不是我的代码,正如您在上面看到的,带有 id="star" 的 img 正在被访问,就好像它是一个对象一样,通常我希望做一些类似的事情
<img scr="..." onmousedown= myFunction() {...}>
或
document.getElementById("star").onmousedown = myFunction() {...}
但不知何故,他们只是通过 id 直接访问 img,我不明白这里的语法,这在任何带有 id 的元素上都可以吗?
编辑:如果是这样,后一个例子什么时候有用?? .getElementById(..(
可以使用id
引用对象来直接访问对象。
star.onmousedown = function myFunction() {...}
是的,可以使用document
中具有id
属性集的任何 HTML 元素直接访问该元素。
是的,您可以使用内置的 JS 函数 getElementById()
获取任何带有 ID 的元素。阅读 MDN 参考以了解更多信息。