gpt4 book ai didi

javascript - Ajax : only call the ajax if element existing

转载 作者:行者123 更新时间:2023-11-29 17:58:24 24 4
gpt4 key购买 nike

例如,我有一个 .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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com