.width ( http://api.jquery.com/width/ ) 和 .height ( http://api.jquery.com/height/ ) 不是属性而是 jquery 函数,所以这段代码有效:
http://jsfiddle.net/nQvK3/1/
$(".popup_pics").each(function(index, domElement) {
if (domElement.clientWidth > 649) {
alert(domElement.id + ' is bigger then 649: ' + $("img.popup_pics").width());
}
else {
alert(domElement.id + ' is smaller then 649: ' + $("img.popup_pics").width());
}
});
我添加了更多代码,这是新的小提琴:http: //jsfiddle.net/nQvK3/4/
- 首先对您的图像源进行 ajax 调用(我在小提琴中将其注释掉,因为我无法对您的源进行 ajax 调用)
- 当 ajax 调用成功时,我们调用 showImages 函数并将响应对象作为第一个参数传递
- 这个函数使用 jquery 来遍历图像数组
- 对于每个图像,我们创建一个图像标签,然后将图像添加到 dom
- 我们最后测量它的宽度,如果它更大,我们对它应用一个类来调整它的大小
//-- 更新代码
$(document).ready(function() {
/*
var request = $.ajax({
url: "images.php?gallery_id=1",
type: "GET",
data: {id : menuId},
dataType: "json"
});
request.done(function(ajaxImagesResultObject) {*/
// this is what ajax returns to you, probably an array of objects
// to test it in your code uncomment the ajax call and comment out the following object
var ajaxImagesResultObject = { imagesArray:
[
{
name: 'stackoverflow small',
url: 'http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png'
},
{
name: 'stackoverflow big',
url: 'http://cdn.sstatic.net/stackexchange/img/logos/careers/careers-logo.png'
}
]
};
console.log(ajaxImagesResultObject);
showPics(ajaxImagesResultObject);
/*});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
*/
});
var showPics = function(ajaxImagesResultObject) {
// foreach image that is contained in the result array
$.each(ajaxImagesResultObject.imagesArray, function(index, imageData) {
var imageElement = $('<img src="' + imageData.url + '" id="' + index+1 + '" title="' + imageData.name + '" />');
// now we add (append) the image inside of the imagesBox element
$('#imagesBox').append(imageElement);
// now we check its width and if it is bigger then 649 we add a resize class
// to save bandwidth images that are too big should get resized on the server not the client
if ($('#' + index+1).width() > 649) {
$('#' + index+1).addClass('imageResizer');
} else {
// do nothing
}
});
};