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