2010-06-21 94 views
0

我想要得到div中的所有标签,代码的一部分工作在Firefox中,不工作IE。任何想法。提前致谢。.each()在IE中不工作

<div id='discounts'> 
    <label id="discount1"> discount 1</label> 
    <label id="discount2"> discount 2 </label> 
    <input type="text" id="discountmisc" value="" />  
</div> 

var selectLabels = { 

    getLabels: function() { 
     $('#discounts > label').each(function(index, item) { 
      alert(index + $(item).attr('id')); 
     }); 
    } 
}; 

selectLabels.getLabels(); 
+3

你得到了什么JavaScript错误?如果有的话。 – 2010-06-21 04:04:18

+0

-1 for“not working”and not reporting'$('#discounts> label')length' – 2010-06-21 04:12:28

+0

'.each()'懒惰地工作,顺便说一句,所以pst的检查是没有必要的。此外,检查'if($('#discounts> label').length> 0)'通常比较慢(因为人们通常不会缓存DOM查询)。在$ {([])。each(function(){alert('hey!');});'vs'$([1])。each(function(){ alert('hey!');});' – 2010-06-21 04:22:30

回答

2

您是否包装在DOM Ready功能中?即

$(function() { 
    var selectLabels = { 
     getLabels: function() { 
      $('#discounts > label').each(function(index, item) { 
       alert(index + $(item).attr('id')); 
      }); 
     } 
    }; 

    selectLabels.getLabels(); 
}); 

或交替:

var selectLabels = { 
    getLabels: function() { 
     $('#discounts > label').each(function(index, item) { 
      alert(index + $(item).attr('id')); 
     }); 
    } 
}; 

$(selectLabels.getLabels); 

终于还是(因为你不关心的返回值):

var selectLabels = { 
    getLabels: function() { 
     $(function() { 
      $('#discounts > label').each(function(index, item) { 
       alert(index + $(item).attr('id')); 
      }); 
     }); 
    } 
}; 

selectLabels.getLabels(); 

告诉我,如果是这样,我会改变我的答案。

+0

这是足够的选择,呃?哈哈,:P – 2010-06-21 04:12:45