2011-10-18 40 views
0

任何更好的方法来做到这一点(假设我有10 a元素,例如)?将相同的功能应用于很多元素(按顺序)

$('#id > a:nth-child(1)').click(function() { changeP(1); return false; }); 
$('#id > a:nth-child(2)').click(function() { changeP(2); return false; }); 
$('#id > a:nth-child(3)').click(function() { changeP(3); return false; }); 

我知道2级的可能性,但我并不特别喜欢它们:使用.bind()与参数,而不是使用.map(return $(this)).click()

  • 然后迭代与索引变种
  • 阵列之上

    回答

    3

    你可以这样做:

    $('#id > a').each(function(i) { 
        $(this).click(function() { changeP(i); return false; }); 
    }); 
    

    jQuery将传递作为第一个参数“每个”功能所选择的元素的索引。

    +0

    +1比'index()',它必须遍历所有的兄弟元素,并计算它们的数量。 – bobince

    2

    您可以使用满足index的元素获得元素的索引(相对于它的父元素) HOD:

    $("#id > a").click(function() { 
        changeP($(this).index() + 1); 
        return false; 
    }); 
    

    您需要在1这样做是因为jQuery的方法往往适用于匹配的集合中的所有元素加1,因为元素的索引从0开始,而nth-child开始,所以click事件处理程序绑定到与选择器匹配的所有元素。

    +0

    如果还有其他元素(不是''')在两者之间?这不会导致错误的索引? –

    +0

    嗯。是的,非常真实的... –

    +0

    你可以“窃取”我答案的一部分;)(缓存选定的元素并执行$ a.index(this)')。或者你可以'$(this).index(“#id> a”)'。 –

    0
    $('#id > a').click(function(){ 
        changeP($(this).index(' #id > a')+1); 
        return false; 
    }); 
    

    参见:index()

    这个工程即使其他元素插入到代码:

    <div id="id"> 
        <a href="#">1</a> 
        <span>hello</span> 
        <a href="#">2</a> 
        <a href="#">3</a> 
        <a href="#">4</a> 
    </div> 
    
    +0

    这将得到相对于所有'a'元素的索引,而不仅仅是'#id> a'。 –

    +0

    已更新的答案。 – artlung

    0
    $.each($('#id > a'), function(index) { 
        $(this).click(function() { 
        changeP(index); return false; }); 
    }); 
    
    0

    你要找的。每():http://api.jquery.com/each/

    $('#id > a').each(function(index){ 
        $(this).click(function(){ 
         changeP(index+1); 
        }); 
    }); 
    
    相关问题