在jQuery中eq()和get()方法的区别
在本文中,我们将讨论jQuery中的eq()和get()方法之间的所有差异。
eq() 方法
此方法用于直接定位所选元素,并返回具有特定索引的元素。
语法:
$(selector).eq(index)
示例: 在本例中,我们将在第0段和第2段设置不同的文本颜色.
<!DOCTYPE html>
<html>
 
<head>
    <title>jQuery eq() Method</title>
     
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
</head>
 
<body style="text-align: center;">
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
     
    <h3>jQuery eq() Method</h3>
 
 
    <p class="text">HTML</p>
 
 
    <p class="text">CSS</p>
 
 
    <p class="text">JavaScript</p>
 
 
 
    <script>
        (document).ready(function () {
            (".text").eq(0).css("color", "red");
            $(".text").eq(2).css("color", "blue");
        });
    </script>
</body>
 
</html>
输出:

get() 方法
该方法使用GET HTTP请求从服务器加载数据。这个方法返回XMLHttpRequest对象。
语法:
$.get( url, [data], [callback], [type] )
示例: 在本例中,我们将从服务器获取数据并将其显示在屏幕上。这段代码将在服务器上运行。
文件名: gfg.php
<?php
if( _REQUEST["name"] ) {
   
   name = _REQUEST['name'];
   echo "A ".name . " portal for geeks";
}
   
?>
文件化名: index.php
<!DOCTYPE html>
<html>
 
<head>
    <title>
        CSS get() Method
    </title>
 
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
    </script>
</head>
 
<body style="text-align: center;">
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
 
    <h3>CSS get() Method</h3>
 
    <div id="GFG">
        Welcome to GeeksforGeeks
    </div>
    <br>
 
    <input type="button" id="Geeks" value="Load Data" />
 
    <script>
        (document).ready(function () {
            ("#Geeks").click(function (event) {
                .get(
                    "gfg.php", {
                    name: "Computer Science"
                },
                    function (data) {
                        ('#GFG').html(data);
                    });
            });
        });
    </script>
</body>
 
</html>
输出:

eq()和get()方法的区别:
| jQuery eq()方法 | jQuery get()方法 | 
|---|---|
| 这个方法以jQuery对象的形式返回元素。 | 这个方法返回一个DOM元素。 | 
| 这个方法检索第n-1个jQuery对象。 | 这个方法返回第n-1个DOM元素。 | 
| 这个方法从集合中的一个元素创建一个新对象并返回该对象。 | 这个方法检索与jQuery对象匹配的DOM元素。 | 
| 它在具有所选元素索引的元素中的返回方法。 | 它有助于使用HTTP GET请求从服务器加载数据。 | 
它的语法是:$(selector).eq(index) | 
它的语法是:$.get(URL,data,function(data,status,xhr),dataType) | 
| 它接受一个参数作为索引。 | 它接受一个参数作为URL。 | 
极客教程