如何从jQuery选择器中获取DOM元素? [英] How to get a DOM Element from a jQuery selector?

查看:56
本文介绍了如何从jQuery选择器中获取DOM元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难从jQuery选择器中找到实际的 DOMElement .

I'm having an impossibly hard time finding out to get the actual DOMElement from a jQuery selector.

示例代码:

<input type="checkbox" id="bob" />
var checkbox = $("#bob").click(function() { //some code  } )

在另一段代码中,我试图确定复选框的选中值.

and in another piece of code I'm trying to determine the checked value of the checkbox.

  if ( checkbox.eq(0).SomeMethodToGetARealDomElement().checked )
    //do something.

而且,我不想这样做:

  if ( checkbox.eq(0).is(":checked"))
    //do something

这使我绕开了复选框,但其他时候,我需要真正的 DOMElement .

That gets me around the checkbox, but other times I've needed the real DOMElement.

推荐答案

您可以通过以下方式访问原始DOM元素:

You can access the raw DOM element with:

$("table").get(0);

或更简单地说:

$("table")[0];

但是实际上并不需要很多(据我的经验).以您的复选框示例为例:

There isn't actually a lot you need this for however (in my experience). Take your checkbox example:

$(":checkbox").click(function() {
  if ($(this).is(":checked")) {
    // do stuff
  }
});

更"jquery'ish",(imho)更简洁.如果要给他们编号怎么办?

is more "jquery'ish" and (imho) more concise. What if you wanted to number them?

$(":checkbox").each(function(i, elem) {
  $(elem).data("index", i);
});
$(":checkbox").click(function() {
  if ($(this).is(":checked") && $(this).data("index") == 0) {
    // do stuff
  }
});

其中一些功能还有助于掩盖浏览器中的差异.一些属性可以不同.经典示例是AJAX调用.要在原始Javascript中正确执行此操作,对于 XmlHttpRequest 大约有7个后备案例.

Some of these features also help mask differences in browsers too. Some attributes can be different. The classic example is AJAX calls. To do this properly in raw Javascript has about 7 fallback cases for XmlHttpRequest.

这篇关于如何从jQuery选择器中获取DOM元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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