This pretty little jQuery code seems to not work.. anyone know why?
If I run it. It returns no errors. And in firebug it does in fact select the proper elements in the DOM.
If I break it apart and do something like this :
$('img[hspace]').css('marginLeft', ($('img[hspace]').attr('hspace') / 2) + 'px')
That works.
Here's the monster in its entirety.
$('img[hspace]').each(function(el){
var pixels = parseInt($(el).attr('hspace'));
if(isNa开发者_C百科N(pixels) || pixels < 1)
pixels = 0;
else
pixels = pixels / 2;
$(el).css('marginLeft', pixels + 'px')
.css('marginRight', pixels + 'px')
.removeAttr('hspace');
});
Update
My 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>
</p>
<p>
</p>
<p>
</p>
<p>
</p>
<p>
</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>`
The each function passes in the index as the first parameter, not the element. You probably want to do $(this)
rather than $(el)
.
el
references the index of the element in the collection and not the element. Either
- add a second parameter to the function, this will be the element.
- use
this
inside of the function.this
references the element
精彩评论