Javascript 只选择 jQuery 集合中的一个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2147437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:57:38  来源:igfitidea点击:

Selecting only one element in the jQuery collection

javascriptjquery

提问by Andrew Smith

How do I limit an event to a single element in a jQuery collection?

如何将事件限制为 jQuery 集合中的单个元素?

In the case below, I've tried using .one()to limit the behaviour (inserting the <li class='close'>Close</li>line of HTML) to a single instance. The behaviour does indeed happen only once, but on EVERY matched element of $( "ul>li>a" ). How do I make it happen only once, to only ONE of the matched elements in the collection?

在下面的情况下,我尝试.one()将行为(插入<li class='close'>Close</li>HTML 行)限制为单个实例。该行为确实只发生一次,但在$( "ul>li>a" ). 如何让它只发生一次,只发生在集合中的一个匹配元素上?

Any ideas?

有任何想法吗?

$( "ul>li>a" ).one(
 "click",    
 function(){
  $( "ul ul")
  .prepend("<li class='close'>Close</li>")
 }
 ); 

Thanks in advance.

提前致谢。

-AS

-作为

回答by Luca Matteis

A jQueryselection returns an array. Therefore $("selection")[0]can work. However there are better abstracted methods for this, like .get(0)or .first()(in case you're looking for the first element of the selection/array).

jQuery选择返回一个数组。因此$("selection")[0]可以工作。但是,有更好的抽象方法,例如.get(0)or .first()(如果您正在寻找选择/数组的第一个元素)。

$("selection").get(index)returns the pure DOM element (at that specific index) of the selection, and is notwrapped in the jQuery object.

$("selection").get(index)返回选择的纯 DOM 元素(在该特定索引处),并且包含在 jQuery 对象中。

$("selection").first()returns the firstelement of the selection, and wrapsit in a jQuery object.

$("selection").first()返回选择的第一个元素,并将其包装在一个 jQuery 对象中。

So if you don't necessarely want to return the firstelement, but still want jQuery functionality, you can do $($("selection").get(index)).

因此,如果您不需要返回第一个元素,但仍需要 jQuery 功能,则可以执行$($("selection").get(index)).

Given your situation, this should work fine:

鉴于您的情况,这应该可以正常工作:

// bind the 'onclick' event only on the first element of the selection
$( "ul>li>a" ).first().click(function() {
    $( "ul ul").prepend("<li class='close'>Close</li>");
}); 

Which is equivalent to this:

这相当于:

$($( "ul>li>a" ).get(0)).click(function() {
    $( "ul ul").prepend("<li class='close'>Close</li>");
});

And this:

和这个:

$($( "ul>li>a" )[0]).click(function() {
    $( "ul ul").prepend("<li class='close'>Close</li>");
});


I must disagree with Ryan, working on the CSS selection string to filter the result is rather expensive compared to the native JavaScript array functionality.

我必须不同意 Ryan,与原生 JavaScript 数组功能相比,使用 CSS 选择字符串来过滤结果是相当昂贵的。

回答by Felix Kling

Try first(), it selects the first element:

Try first(),它选择第一个元素:

$( "ul>li>a" ).first().one('click',    
     function(){
        $( "ul ul").prepend("<li class='close'>Close</li>")
     }
 ); 

one()is used, as you already noticed, to handle an event only once.

one()正如您已经注意到的,用于仅处理一个事件一次

回答by Ryan

You have to specify the index of the element you want to work with.

您必须指定要使用的元素的索引。

If your selector returns more than one element you can do one of a couple things... You can isolate your elements by giving them a class or id attribute in your html and alter the selector to select only the class/id of the element/s you wish to select or you can specify the index of the element you're trying to work with. The later method is a bit sloppy but works as long as your page structure doesn't ever change.

如果您的选择器返回多个元素,您可以执行以下操作之一...您可以通过在 html 中为它们提供 class 或 id 属性来隔离元素,并更改选择器以仅选择元素的 class/id/ s 您希望选择,或者您可以指定您尝试使用的元素的索引。后一种方法有点草率,但只要您的页面结构永远不会改变就可以工作。

So for the first method I spoke of you'd change your selector to this after applying a class/id to your elements:

因此,对于我提到的第一种方法,在将类/ID 应用于元素后,您会将选择器更改为此:

$("ul>li>a.class")
or
$("ul>li>a#id")

For the second method I mentioned you'd change your selector to this:

对于我提到的第二种方法,您可以将选择器更改为:

$("ul>li>a:eq(index)")

Where index is the zero based index of the element you're trying to select.

其中 index 是您尝试选择的元素的从零开始的索引。

回答by SLaks

You can call the firstmethod, which will return a new jQuery object containing only the first element in the original one.

您可以调用该first方法,该方法将返回一个新的 jQuery 对象,该对象仅包含原始对象中的第一个元素。

However, in your case, you might as well use the (equivalent) :firstselector, like this:

但是,在您的情况下,您不妨使用(等效):first选择器,如下所示:

$("ul > li > a:first").click(function() { ... });

If you only want to handle the first clickevent and ignore any subsequent clicks, you'll need to use .one(), like you already are.

如果您只想处理第一个click事件并忽略任何后续点击,则需要使用.one(),就像您已经使用的那样。

回答by kgiannakakis

You need to combine first() with one():

您需要将 first() 与 one() 结合使用:

$( "ul>li>a" ).first().one('click', function () {});

More general:

更一般:

$( "ul>li>a:eq(n)" ).one('click', function () {});