I have a function that searches for images in different ways, one by one, and for each trial, if it finds one, the function returns that image.
The code becomes quite clunky if I search for various images, is there a more elegant way of trying to find an object and returning it if it exists?
var image = $('a.jqzoom')[0].getAttribute('href');
if (image)
return image;
Then, I keep trying other ways to find images one after the other, for example:
var image = $('a.asdf')[0].getAttribute('href');
if (image)
return image;
Consider:
return $('a.jqzoom')[0].href || <value if not found>;
so if no element is found, the first part returns undefined and the second value is returned. A more jQuery-ish way is:
return $('a.jqzoom').prop('href') || <value if not found>;
But I'm a bit puzzled, isn't the href of an A element supposed to be a document (or some other text based object), not an image?
If your function doesn't end with the return
statement it has the return value undefined
. So you should just write:
return $('a.asdf')[0].getAttribute('href');
It's basically equivalent to what you already got (it's a little looser, by virtue of the truthy check you got.
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.