2011-12-29 77 views
2

我買了$('#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 
}); 

添加例如使其更清楚:

<!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> 
+1

你有my_id1 vs my_id2 - 標識符不一樣 – Nobita 2011-12-29 11:39:53

+0

你有div與「my_id2」ID ..! – 2011-12-29 11:40:19

+0

用$開始你的變量名有點奇怪 - $ t,$ div1等等 - 僅僅因爲jQuery在任何地方使用$並不意味着你必須這樣做。哦,你認爲它的PHP? – Spacedman 2011-12-29 11:46:52

回答

4

第一返回一個jQuery對象與該div作爲其唯一的成員。你可以在對象上使用jQuery函數來操作它。

第二個使用瀏覽器的內置方法返回DOMElement。

7

不同的是,第一個,而第二返回DOM元素返回jquery對象

但是這些陳述等效

document.getElementById('my_id2') <-> $('#my_id1').get(0) 

document.getElementById('my_id2') <-> $('#my_id1')[0] 
+0

不一定相同。 Internet Explorer將返回其「name」屬性與「getElementById()」中請求的「id」值相匹配的元素,但jQuery庫永遠不會這樣做。 – Pointy 2011-12-29 11:43:16

0

使用my_id1

var $div2 = document.getElementById('my_id1'); 
1
$('#my_id1') // Returns a jQuery object 

而且

getElementById('my_id1') // Returns a DOM object. 

爲了得到一個jQuery對象的DOM對象,你可以撥打:

$('#my_id1').get() 

jQuery的可以匹配更多比選擇一個對象TOR,因此要獲得第二匹配的DOM元素:

$('#my_id1').get(1) // 1 = item #2 (zero-based index) 

而得到匹配從END集合 DOM元素,你可以使用一個負數,從匹配的末端的距離你想要檢索的元素,所以-1得到最後一個項目。

$('#my_id1').get(-1) // gets the last item of the matched elements 
0

根據我的說法,它在瀏覽器中的渲染有所不同。

好像我們不使用文檔。這在IE瀏覽器中不起作用。

但只適用於其他瀏覽器。

相關問題