如何从 jQuery 选择器中获取 DOM 元素?

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

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

问题描述

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

Sample Code:

<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.

And please, I do not want to do:

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

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

解决方案

You can access the raw DOM element with:

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

or more simply:

$("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
  }
});

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
  }
});

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 元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何从 jQuery 选择器中获取 DOM 元素?

基础教程推荐