我有一个元素
<span id="current" data=""></span>
data
属性的值将由异步 AJAX 函数填充。我无法将此函数更改为同步或让它返回值。
这是部分代码
$("#popup #save").click(function () {
//setting a lot of vars here
var id = $("#current").val();
if (id == '') {
//new so insert
$.ajax({
type: "GET",
url: myurl,
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#loadstatus").html('');
//returns new id
if (data > 0) {
$('#current').val(data);
}
}
});
}
else {
//existing so update
//more code
}
return false;
});
var id = $("#current").val();
if (id == '') {
//save
$("#popup #save").click(); //this function contains the AJAX call which also sets `$("#current").val()` with a value returned in that same AJAX call
//I can only set the value of id after the success of the aforementioned AJAX function
//so here I need to set some sort of timeout
id = $("#current").val();
}
我想执行另一个函数,但在该函数中我想等到属性data
不等于空。
我正在查看这个:http://javascriptisawesome.blogspot.com/2011/07/faster-than-jquerydocumentready-wait.html
但我更喜欢使用默认的 jQuery 来完成此操作。
我该怎么做?
最佳答案
您可以轮询数据的值(value):
function check() {
if (!$('#current').attr('data')) {
return setTimeout(check, 1000);
}
// do work here
}
check();
关于jQuery 等待元素属性有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27370227/