HTML DOM元素全球范围 [英] HTML DOM Elements Global Scope

查看:74
本文介绍了HTML DOM元素全球范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当帮助某人时,我有一个有趣的情况。他们想知道为什么下面的代码工作:

 < input type =textid =myElemvalue =Nice /> 
$ b $(function(){
var myElem = $(myElem);
myProblem();
});

var myProblem = function(){
var result = myElem.value; // This Works
result = myElem.val(); //不起作用
}

起初我没有很好的答案,因为我目前的想法是myProblem方法中的两个语句都会失败,但只有一个失败。后来我学会了浏览器对全部HTML元素进行全局范围的测试。



因此,解释这个问题是如何解决的,myElem将在加载函数中作为JQuery对象当它位于myProblem方法内时,JQuery对象将变得超出范围,并且由于浏览器将全部范围内的所有HTML元素都包含在内,myElem将作为HtmlInputElement的作用域。



I我一直在编写代码,而对于我来说,只是学习浏览器对全局HTML元素进行范围界定是我的新闻。

我了解代码示例及其工作原理。我的问题是浏览器有多早这样做?这是最新的趋势还是我错过了什么?是否所有的浏览器都支持这个功能?

经过一番调查,我发现了最新的浏览器支持,但是IE6 +等如何?

谢谢

解决方案


我了解代码示例,我的问题是浏览器有多早就这样做了,这是最新的趋势还是我错过了一些东西?所有的浏览器都支持这个吗?

这原本是一个非标准的IE功能。如果我回想起来,Opera可能是第一个采用它的人,接下来是Chrome。

最近,Firefox采用了它。因此,喜欢它或讨厌它,大多数现代浏览器都实现此功能,但如果您支持传统浏览器,则会发现一些(特别是Firefox)没有它。



许多人建议不要依赖此功能。最终取决于你和你的项目必须支持的浏览器。


When helping someone, I had an interesting situation. They wondered why the code below worked:

<input type="text" id="myElem" value="Nice" />

$(function() {
    var myElem = $("myElem");
    myProblem();
});

var myProblem = function() {
    var result = myElem.value; //This Works
    result = myElem.val(); //Doesn't Work
}

At first I didn't have a good answer, because my current thinking is both statements in the myProblem method should fail, but only one failed. Later I learned browsers scope all HTML elements globally.

So explaining how this problem is solved is by myElem will be in scope as a JQuery object within the on load function, however the JQuery object will become out-of-scope when it is inside myProblem method and, because browsers scope all HTML elements globally, myElem will be scoped as a HtmlInputElement.

I have been writing code for awhile, and for me to just learn browsers are scoping all HTML elements globally was news to me.

I understand the code sample and why it works. My question is how early have browsers been doing this? Is this a latest trend or have I missed something? Do all browsers support this?

After some research, I found the latest browsers support, but how about IE6+, etc.

Thank you

解决方案

"I understand the code sample and why it works. My question is how early have browsers been doing this? Is this a latest trend or have I missed something? Do all browsers support this?"

This was originally an IE feature that was non-standard. If I recall, Opera may have been first to adopt it, followed by Chrome when it came around.

More recently, Firefox has adopted it. As such, love it or hate it, the majority of modern browsers implement this feature, but if you're supporting legacy browsers, you'll find some (especially Firefox) that do not have it.

Many recommend to not rely on this feature. Ultimately up to you and what browsers your project must support.

这篇关于HTML DOM元素全球范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆