jQuery $()与document.getElementByID - 差异 [英] jQuery $() vs. document.getElementByID -- differences

查看:68
本文介绍了jQuery $()与document.getElementByID - 差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

document.getElementById vs jQuery

更多jQuery新手对你造成伤害伙计们......

More jQuery newbieisms to inflict on you folks...

我有一些代码可以或多或少地使用jQuery。我的困惑在于,在一个案例中,我得到了一个标识符,该标识符是页面上div的ID。我希望$(theIdentifier)能够抓住这个对象,但事实并非如此; console.log返回'undefined'。但是,document.getElementById(theIdentifier)成功 - 它返回我正在寻找的东西,并且对div的进一步操作按预期工作。

I have some code that is using jQuery more or less happily. My confusion is that, in one case, I get my hands on an identifier which is the ID of a div on the page. I expect that $(theIdentifier) will get its hands on the object, but it doesn't; console.log returns 'undefined'. However, document.getElementById(theIdentifier) succeeds -- it returns the thing I'm looking for, and further operations on the div work as expected.

这里有什么?它们不应该相同吗?为什么jQuery版本不工作?

What's up here? Shouldn't they be identical? Why isn't the jQuery version working?

显然很困惑;感谢任何建议!

Puzzled, obviously; thanks for any advice!

推荐答案

$()的参数必须是选择器

The argument to "$()" has to be a selector:

var $thing = $("#" + thingId);

几乎与调用getElementById()相同。不同之处在于后者将关注id值(IE中除外,见下文),而基于jQuery选择器的代码将关注嵌入式CSS元字符。因此,如果你有一个带有。的id值。在其中,像这样:

That's almost the same as calling "getElementById()". The difference is that the latter will only care about "id" values (except in IE, see below), while the jQuery selector-based code will pay attention to embedded CSS metacharacters. Thus, if you've got an "id" value with a "." in it, like this:

var foo = $('#thing.special');

然后会查找ID为thing且类为special的元素,而不是ID为thing.special的元素。

then that will look for an element with id "thing" and class "special", instead of an element with the id "thing.special".

IE的问题:由于微软的一些神秘开发人员所知,IE中的getElementById()代码将返回name属性与参数匹配的元素。该行为不依赖于具有相同id值的元素的存在;我认为它返回它在DOM中找到的第一个。 (我在这方面不了解IE9。)

The thing with IE: for reasons known only to some mysterious developers at Microsoft, the "getElementById()" code in IE will return elements whose "name" attribute matches the argument. That behavior is not dependent on the presence of an element with the same "id" value; I think it returns the first one it finds in the DOM. (I don't know about IE9 in this regard.)

注意—注释正确地提到$()函数可以采用各种不同类型的参数,从而产生各种效果。当我说它必须是一个选择器时,我指的是它与字符串值参数的使用。

Note — a comment mentions correctly that the "$()" function can take a variety of different types of arguments, resulting in a variety of effects. When I said it "has to be a selector", I was referring to its use with string-valued arguments.

这篇关于jQuery $()与document.getElementByID - 差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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