这个相当小的jQuery代码似乎不起作用..任何人都知道为什么?

时间:2010-07-27 20:43:05

标签: javascript jquery refactoring

如果我运行它。它不返回任何错误。在firebug中,它确实选择了DOM中的适当元素。

如果我把它拆开并做这样的事情:

$('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>`

2 个答案:

答案 0 :(得分:7)

每个函数passes in the index as the first parameter, not the element。您可能希望$(this)而不是$(el)

答案 1 :(得分:4)

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

  • 向函数添加第二个参数,这将是元素。
  • 在函数内部使用thisthis引用元素