如何将这个jQuery函数仅应用于某个类 [英] How to apply this jQuery function to a certain class only

查看:96
本文介绍了如何将这个jQuery函数仅应用于某个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  $('a')。each(function(){
var clicked = false;
$(this).bind('click',function (){
if(!clicked)return!(clicked = true);
});
});

大家好。我试图弄清楚如何将这个函数应用到< a> 元素中,该元素也包含一个名为 touch 。换句话说:



功能 应用于此:

 < a href =#class =touch> 

功能不适用于此:

 < a href =#> 

对不起,我是jQuery newb。

解决方案

您需要类别选择器(合并与您当前的元素选择器):

< pre $ $('a.touch')。each(function(){
var clicked = false;
$(this).bind('click', function(){
if(!clicked)return!(clicked = true);
});
});

值得通读jQuery API(特别是选择器部分)。它将为您节省很多时间!



值得注意的是,大多数jQuery选择器与CSS选择器相同。如果你知道关于CSS的任何信息,你也可以将这些知识应用到jQuery中。




另外,由于大多数jQuery方法适用于匹配集中的每个元素,您可能会摆脱每个循环。如果我理解正确,那么您试图阻止每个 a.touch 元素在第一次点击链接后跟随链接。如果这是正确的,那么你可以这样做:

  $('a.touch')。one(click,函数(){
返回false;
});


$('a').each(function() {
    var clicked = false;
    $(this).bind('click', function() {
        if(!clicked) return !(clicked = true);
    });
});

Hi all. I'm trying to figure out how to apply this function to only <a> elements that also contain a class called touch. In other words:

function is applied to this:

<a href="#" class="touch">

function is not applied to this:

<a href="#">

Sorry, I'm a jQuery newb.

解决方案

You need a class selector (combined with your current element selector):

$('a.touch').each(function() {
    var clicked = false;
    $(this).bind('click', function() {
        if(!clicked) return !(clicked = true);
    });
});

It's worth having a read through the jQuery API (in particular the selectors section). It will save you a lot of time later on!

It's also worth remembering that the majority of jQuery selectors are the same as the CSS selectors. If you know anything about CSS, you can apply that knowledge to jQuery too.


On a separate note, since most jQuery methods apply to every element in the matched set, you can probably get rid of your each loop. If I've understood correctly, you are trying to prevent every a.touch element from following the link the first time it is clicked. If that's right, then you can just do this:

$('a.touch').one("click", function() {
    return false; 
});

这篇关于如何将这个jQuery函数仅应用于某个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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