是否有一种在jquery中迭代多个选择器的正确方法

时间:2012-06-30 12:49:02

标签: jquery

假设我有一个.on()函数,其中我选择了多个ID

    $("#i, #am, #your, #father").on("click" , function(event){
    //iterate over the selectors and return tagname
       alert ( $("#i").prop("tagName")  );
       alert ( $("#am").prop("tagName") );
       alert ( $("#your").prop("tagName") );
       alert ( $("#father").prop("tagName") );
    }

我能想到的唯一方法是分别提醒每个人。是否有一种已知的方法将$("#i, #am, #your, #father")作为一种数组处理?

2 个答案:

答案 0 :(得分:3)

请试试这个:

有趣的阅读:jQuery: What's the difference between '$(this)' and 'this'?

同样点击这些链式ids中的任何一个,您可以使用$(this)获取道具tagName

此外,如果您想知道如何将所有这些内容绑定到var上,请参阅此处:$foo示例:http://jsfiddle.net/6hwLS/5/

希望这有帮助,

$("#i, #am, #your, #father").on("click" , function(event){
//iterate over the selectors and return tagname
   alert($(this).prop("tagName")  );

}

进一步您也可以这样做

var $foo = $("#i, #am, #your, #father");

$foo.on("click", function(event) {
    //iterate over the selectors and return tagname
    alert($(this).prop("tagName"));

}​

答案 1 :(得分:2)

这样的东西?

var $groupSelection = $('#i, #am, #your, #father');

$groupSelection.on('click', function(e){
   $groupSelection.each(function(){
      alert( $(this).prop('tagName') );
   });
});

演示 http://jsfiddle.net/ZHpFa/