您的直接答案是:将srcElement
更改为target
。 Mozilla开发者网络是一个很好的(很多)资源之一,用于检查标准符合性。 A visit to their site对于srcElement
表示它是非标准的,并以正确的方式提出建议(target
)。
不幸的是,即使是标准的API也不一定适用于所有浏览器。通常,一个标准的部分被实现了piecemail。使用权威来源进行检查对于了解哪些地方支持至关重要。
其他资源:
至于你明确的问题:
“我的问题是,有没有更‘正确’的方式来访问这些数据,会为所有浏览器中工作,或者我需要检查我是什么浏览器,并根据浏览器访问一个不同的方式信息正在使用?”
使用标准和检查支持(通过我上面提供的资源)必须在跨浏览器代码的最好机会。
不写检查浏览器类型和版本,看看你的代码将运行(浏览器检测)的代码,因为:
- 有太多的浏览器和太多的版本 - 这很烂!
- 浏览器可以和会骗你对他们是什么!
使用 “功能检测” 有疑问时。特征检测是评估特征是否存在的代码,如果存在则使用它。如果它没有提供回退。下面是IE8(或更低)的浏览器很常见的一个还不支持W3C标准的事件处理:
// Here we are attempting to obtain the value of the
// addEventListener property of the window object.
// IE 8 doesn't implement this property so "undefined"
// will be returned. But, because we are attempting to
// use the value as the condition of an if/then construct
// "undefined" will be converted to a boolean. "undefined"
// is a "falsey" value, so it will convert to false.
// This means that if the else portion of our construct
// is reached, we have a browser that doesn't support
// addEventListener
if(window.addEventListener){
// W3C standards are supported - do things the standard way
obj.addEventListener("click", someFunction, capture);
} else {
// Must be IE 8 or less - do things the IE way
obj.attachEvent("onclick", someFunction);
}
这只是一个方式来使用功能检测,但它通常取决于一个值转换成一个布尔值。查看更多关于它here。
看看[Document.querySelector(https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector)(这也适用于HTML元素)。 – gyre