.each() method only applies to first element in IE

血红的双手。 提交于 2020-01-15 05:48:09

问题


I have a jQuery like so:

$('#corner .photo img').each(function() {
    var $img = $(this);
    var h = $img.height();
    var w = $img.width();
    $img.css('margin-top', +h / -2 + "px").css('margin-left',+ w/ -2 + "px");
});

It works in all browsers except in IE 7 and 8. In those browsers, it only applies the new property to the first element of #corner (which is the first .photo img).

If I remove #corner, it applies to all instances of ".photo img" inside it. However, I cannot remove the id #corner because some other parts of the HTML are using ".photo img" and I don't want this jQuery script to be applied to all. I only want it to be applied inside #corner.

Is there a way to solve this?

EDIT:

My bad, apparently there are multiple divs with the same name in the document, which are causing the problems in IE. I changed them to classes and it now works.


回答1:


You can try

$('#corner').find('.photo img').each(...

By the way, IE does not like multiple items with the same ID. If you are using it this way with multiple id="corner" items them change that to a class and you should be fine.



来源:https://stackoverflow.com/questions/7785138/each-method-only-applies-to-first-element-in-ie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!