gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:01:22 25 4
gpt4 key购买 nike

我认为 $('#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>

最佳答案

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

但是这些语句是等效的:

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

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

关于javascript - jquery $ ('#my_id' ) 和 document.getElementById ('my_id' ) 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8667388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com