我正在检查单击一个按钮,图像是否存在于 <ul>
中标签与否。为此,我正在使用这个函数:
function check_image_exists(){
$('ul#show_uploaded_images').each(function() {
if ($(this).find('img').length) {
return true;
}else{
return false;
}
});
}
现在,如果我把这个东西放在点击函数中,它就会起作用......
function insert_product(){
$('ul#show_uploaded_images').each(function() {
if ($(this).find('img').length) {
alert("Image found");
}else{
alert("Not found");
}
});
}
但是,如果我将两者分开并尝试仅使用返回值来决定我的条件,那么它就不起作用。 :
function check_image_exists(){
$('ul#show_uploaded_images').each(function() {
if ($(this).find('img').length) {
return true;
}else{
return false;
}
});
}
function insert_product(){
var image_exist = check_image_exists();
if(image_exist == false){
alert("not found")
}else{
do the rest.....
}
}
最佳答案
问题是您试图在 each
回调中返回一个值,但这没有任何意义,因此返回值会被吞掉。
有一种更简单的方法可以做到这一点。只需检查 .find()
是否返回任何元素:
var thereAreImages = $('ul#show_uploaded_images').find('img').length !== 0;
或者将其封装在函数中:
function check_image_exists() {
return $('ul#show_uploaded_images').find('img').length !== 0;
}
function insert_product() {
if (check_image_exists()) {
// do the rest...
} else {
console.log('not found');
}
}
关于javascript - 检查 <ul> 标签内是否存在图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27561386/