And*_*ith 12 javascript jquery
如何将事件限制为jQuery集合中的单个元素?
在下面的例子中,我尝试使用.one()限制行为(插入<li class='close'>Close</li>HTML行)到单个实例.这种行为确实只发生过一次,但是对于每个匹配的元素$( "ul>li>a" ).如何只对集合中的一个匹配元素进行一次?
有任何想法吗?
$( "ul>li>a" ).one(
"click",
function(){
$( "ul ul")
.prepend("<li class='close'>Close</li>")
}
);
Run Code Online (Sandbox Code Playgroud)
提前致谢.
-如
Luc*_*eis 26
甲jQuery选择返回一个数组.因此$("selection")[0]可以工作.然而,有更好的抽象方法,如.get(0)或.first()(如果你正在寻找选择/数组的第一个元素).
$("selection").get(index)返回选择的纯DOM元素(在该特定索引处),并且不包含在jQuery对象中.
$("selection").first()返回选择的第一个元素,并将其包装在jQuery对象中.
因此,如果您不是必须要返回第一个元素,但仍然需要jQuery功能,那么您可以这样做$($("selection").get(index)).
鉴于你的情况,这应该工作正常:
// 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>");
});
Run Code Online (Sandbox Code Playgroud)
这相当于:
$($( "ul>li>a" ).get(0)).click(function() {
$( "ul ul").prepend("<li class='close'>Close</li>");
});
Run Code Online (Sandbox Code Playgroud)
还有这个:
$($( "ul>li>a" )[0]).click(function() {
$( "ul ul").prepend("<li class='close'>Close</li>");
});
Run Code Online (Sandbox Code Playgroud)
我必须不同意Ryan,使用CSS选择字符串来过滤结果与原生JavaScript数组功能相比相当昂贵.
尝试一下first(),它选择第一个元素:
$( "ul>li>a" ).first().one('click',
function(){
$( "ul ul").prepend("<li class='close'>Close</li>")
}
);
Run Code Online (Sandbox Code Playgroud)
one()正如您已经注意到的,仅用于处理事件一次。