javascript - Ajax : only call the ajax if element existing

标签 javascript jquery ajax

例如,我有一个 .ajax() 函数,如下所示:

function trend() {
    return $.ajax({
        url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
        type: 'get',
        success: function(data) {

        }
    });
}

它工作正常,但我想添加一个 if 语句来检测 $(".numberOfProfile0").html() 是否存在,并且仅在 $(".numberOfProfile0").html()存在

我尝试了下面,但似乎不正确

if ($(".numberOfProfile0").length) {
    function trend() {
        return $.ajax({
            url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
            type: 'get',
            success: function(data) {

            }
        });
    }
}

-更新:

让我们展示整个应用程序 这是函数:

  if($(".numberOfProfile0").html().length){
                    function trend1() {
                          return $.ajax({
                            url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
                            type: 'get',
                            success: function(data) {

                            }
                          });
                        }
                    }

$.when(trend1()).done(function(trend1_data) {

                        //do something
}

最佳答案

请记住 jQuery 选择器不是字符串。使用 jQuery,执行此操作的正确方法类似于 $('.selector').val().length 、 $('.selector').html().length 在代码中使用 $(".numberOfProfile0").html().length > 0:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="numberOfProfile0">lorem</div>

<script>
if ( $(".numberOfProfile0").html().length > 0 ) {
  
   alert("success");
  
 // your function:
  
   //function trend() {
        //return $.ajax({
           // url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + //$(".numberOfProfile0").html(), //getting the api
           // type: 'get',
            //success: function(data) {

            //}
       // });
   // }
  
  }


</script>

关于javascript - Ajax : only call the ajax if element existing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37129548/

相关文章:

javascript - jQuery,Ajax,PHP发布错误500(内部服务器错误)

javascript - 我需要在正则表达式 javascript 中获得第二组

javascript - URL 替换为 anchor ,而不是替换现有 anchor

javascript - SharePoint 日期和 JavaScript

php - 在显示 HTML 之前检测搜索页面的 Ajax 请求何时返回 0 个结果

javascript - REST 调用 JavaScript

javascript - 如何更改 AJAX 响应 HTML,然后继续在 jQuery 中替换?

密码的 javascript 正则表达式至少包含 8 个字符、1 个数字、1 个大写字母和 1 个小写字母

javascript - 使用 jQuery 用 div 包装不同的 html 标签

javascript - 从 oninput 事件 Javascript/jQuery 获取文本