jquery $('#my_id')和document.getElementById('my_id')之间的区别?

Hak*_*kan 2 javascript jquery

我认为$('#my_id1')和document.getElementById('my_id1')是一样的.但它显然不是.有什么不同?

(function( $ ) {
  $.fn.simple_hide_function = function() {
  var $t = this;
  $t.hide();
  };
})( jQuery );

$(window).load(function () {
var $div1 = $('#my_id1');
var $div2 = document.getElementById('my_id2');
$div1.simple_hide_function(); // this is working
$div2.simple_hide_function(); // but this is not working
});
Run Code Online (Sandbox Code Playgroud)

添加示例以使其更清晰:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>

<div id="my_id1" style="height:100px;background:#f00">div1</div>
<div id="my_id2" style="height:100px;background:#f00">div2</div>



<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>

(function( $ ) {
  $.fn.simple_hide_function = function() {
  var $t = this;
  $t.hide();
  };
})( jQuery );

$(window).load(function () {
var $div1 = $('#my_id1');
var $div2 = document.getElementById('my_id2');
$div1.simple_hide_function();
$div2.simple_hide_function();
});

</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Ali*_*tad 7

区别在于第一个返回jquery对象,而第二个返回DOM元素.

但这些陈述是等价的:

document.getElementById('my_id2') <->  $('#my_id1').get(0)
Run Code Online (Sandbox Code Playgroud)

要么

document.getElementById('my_id2') <->  $('#my_id1')[0]
Run Code Online (Sandbox Code Playgroud)