2010-07-27 53 views
3

如果我運行它。它不返回錯誤。在螢火蟲中,它實際上是在DOM中選擇適當的元素。這個漂亮的小jQuery代碼似乎不工作..任何人都知道爲什麼?

如果我分解並做這樣的事情:

$('img[hspace]').css('marginLeft', ($('img[hspace]').attr('hspace')/2) + 'px') 

工程。

這裏是整個怪物。

$('img[hspace]').each(function(el){ 
    var pixels = parseInt($(el).attr('hspace')); 
    if(isNaN(pixels) || pixels < 1) 
     pixels = 0; 
    else 
     pixels = pixels/2; 
    $(el).css('marginLeft', pixels + 'px') 
     .css('marginRight', pixels + 'px') 
     .removeAttr('hspace'); 
}); 

更新

我的HTML:

`<div class='grid_7'> 
     <p><p> 
      this is mys</p> 
     <p> 
      <img align="left" alt="dude its me" border="10" height="168" hspace="30" src="http://s3.amazonaws.com/hq-photo/root/system/photos/6187/resized_orig/photo.jpg" vspace="10" width="130" /></p> 
     <p> 
      this is as good as it gets</p> 

     <p> 
      this isasd</p> 
     <p> 
      sdfasdfasdfasdfasd</p> 
     <p> 
      asdfasdfasdf</p> 
     <p> 

      asdfa</p> 
     <p> 
      sdfasdfasdf</p> 
     <p> 
      &nbsp;</p> 
     <p> 
      &nbsp;</p> 
     <p> 

      &nbsp;</p> 
     <p> 
      &nbsp;</p> 
     <p> 
      &nbsp;</p> 
     <p> 
      <img align="right" alt="it's also me" border="50" height="168" hspace="50" src="http://s3.amazonaws.com/hq-photo/root/system/photos/6187/resized_orig/photo.jpg" vspace="50" width="130" /></p></p> 
     </div>` 
+1

嘗試改變$(EL)到$​​(本) – Adam 2010-07-27 20:45:28

+1

我建議你傳遞一個基數'parseInt'過的明確性 – 2010-07-27 20:58:34

回答

7

的每個功能passes in the index as the first parameter, not the element。你可能想要做$(this)而不是$(el)

+1

或者 - '函數(IDX,EL){}'應該做的訣竅太... http://api.jquery.com/each – gnarf 2010-07-27 20:47:49

+0

有趣。在我的例子中,'this'不起作用,但'(idx,el)'做到了。而通過工作,我只是表示它沒有錯誤地通過。但是沒有對我的DOM進行實際更改。任何人有任何想法爲什麼?我正在解析的內容來自WYSIYWYG,所以周圍有很多'/ n'。同樣,如果我只是在沒有循環的情況下運行它,它至少會以一個循環爲目標併成功移動它。 – Trip 2010-07-27 20:55:35

4

el引用集合中元素的索引而不是元素。要麼

  • 添加第二個參數給函數,這將是元素。
  • 使用this裏面的函數。 this引用元素
相關問題