简体   繁体   中英

JQuery callback function doesn't work

I'm trying to use callback function of the following type:

$('elem').attr(
'attr',
function(i, val){
    return i*10 + 'px';
   }
);

to place images one on top of another.

My HTML includes five images only.

CSS:

img {
position: absolute;
width: 100px;
height: auto;
}

JQuery:

$('img').attr(
'top',
function(i, val){
    alert(50 + i*110 + 'px');
    return 50 + i*(110) + 'px';
  }
);

Alerts in the page: 50px...160px...270px...380px...490px But images still stuck in one place. Can you find error here?

What you're doing is setting an HTML property, not a CSS property. You image becomes <img top=50px></img> , which to the browser means nothing. Use the jquery .css() function to manipulate css:

$('img').css(
    'top',
    function(i, val){
        return 50 + i*(110) + 'px';
    }
);

Eg. http://jsfiddle.net/M6SZE/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM