javascript - 检查 <ul> 标签内是否存在图像

标签 javascript jquery function return-value

我正在检查单击一个按钮,图像是否存在于 <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/

相关文章:

javascript - React Native - 如何在多个按钮上应用 Prop

javascript - 使用 javascript/jquery 从数据库格式化日期的正确方法

javascript - JQuery - 如何在网页中心放置一个带有 <img> 的 <p>

matlab - 如何在不使用嵌套函数的情况下求解 ODE?

javascript - 使用 "new"表示法将函数设置为对象成员

javascript - Rails 3.2 - 文本字段更改时的 Ajax 调用

javascript - 如何重置 iframe

c# - 通过 ActionLink 提交 Ajax.BeginForm

javascript - 单击后隐藏 DIV (jQuery)

c++ - 将模板传递给 boost 函数