2010-07-27 49 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引用元素
相关问题