jQuery.get() - 实用吗? [英] jQuery.get() - Practical uses?

查看:102
本文介绍了jQuery.get() - 实用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解你为什么要使用 jQuery.get() jQuery.get(index) 。文档说它是将jQuery选择转换为原始DOM对象,而不是将选择作为jQuery对象及其可用的方法。



所以快速例如:

  $(div)。get(0).innerHTML; 

与以下内容相同:



<$ p $ 。p> $( DIV)的HTML();

显然这是一个糟糕的例子,但我很难想象你何时会使用获得()。你能帮我理解我在代码中使用这个方法的时间吗?

解决方案

Cody Lindley(jQuery团队成员)有一个< a href =http://codylindley.com/Webdev/355/jquery-get-caching-dom-nodes-in-an-array =nofollow noreferrer>很好的例子为什么你会用get()


如果你需要缓存一组元素,因为你要删除它们,jQuery get()方法非常方便。例如,在下面的代码中,我将保存数组中页面上的所有< li> 元素,删除它们,然后使用此功能将它们添加回页面阵列。有意义吗?




 < html> 
< head>
< script type =text / javascriptsrc =http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js>< / script>
< / head>

< body>

< ul>
< li> test< / li>
< li> test< / li>
< li> test< / li>
< li> test< / li>
< li> test< / li>
< li> test< / li>
< li> test< / li>
< li> test< / li>
< / ul>

< script>

var test = $('ul li')。get();

$('ul')。empty();

$ .each(test,function(){$('ul')。append('< li>'+ $(this).html()+'new< / li>' );});

< / script>
< / body>
< / html>


I am trying to understand why you would use jQuery.get() and jQuery.get(index). The docs say it is to convert the jQuery selection to the raw DOM object instead of working with the selection as a jQuery object and the methods available to it.

So a quick example:

$("div").get(0).innerHTML;

is the same as:

$("div").html();

Obviously this is a bad example but I am struggling to figure when you would use .get(). Can you help me understand when I would use this method in my code?

解决方案

Cody Lindley (jQuery Team Member) has a great example of why you would use get()

If you ever need to cache a set of elements, because you are about to remove them, the jQuery get() method is really handy. For example, in the code below I am saving all my <li> elements on the page in an array, removing them, and then adding them back into the page using this array. Make sense?

<html> 
<head> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script> 
</head>

<body>

<ul> 
    <li>test</li> 
    <li>test</li> 
    <li>test</li> 
    <li>test</li> 
    <li>test</li> 
    <li>test</li> 
    <li>test</li> 
    <li>test</li> 
 </ul>

<script>

var test = $('ul li').get();

$('ul').empty();

$.each(test, function(){ $('ul').append('<li>'+$(this).html() + ' new</li>'); });

</script> 
</body> 
</html>

这篇关于jQuery.get() - 实用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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