2010-06-21 93 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