jQuery等待元素属性具有某个值

5
我有一个元素。
<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实现。 我该如何做?

1
你在使用什么 AJAX 函数?你是在使用 $.post、$.get 还是 $.ajax?你能否在 AJAX 调用的 success 函数中直接调用第二个函数? - Michael
为什么你不能更改这个函数?它来自一个库吗?代码是什么? - Ja͢ck
这是一个相当长的函数,有很多变量被设置,然后执行了一个 $.ajax({ type: "GET" - Adam
1
我会在Ajax成功后使用回调函数;如果不能,那么就挂钩(span元素上的)更改事件。 - Lea
请在您的问题中显示$.ajax(...)代码块。 - Ja͢ck
3个回答

9
你可以轮询数据的值:
function check() {
    if (!$('#current').attr('data')) {
        return setTimeout(check, 1000);
    }

    // do work here
}

check();

3
您可以使用超时来定期检查值是否不再为空。 http://jsfiddle.net/Delorian/1g932hj8/ 注意1:我将您的span更改为输入以允许您在JS Fiddle中更新它,但如果它是一个span,代码也将正常工作。
注意2:这是一个递归函数,它在睡眠2秒后调用自身以重新检查值。 如果您正在实现此功能,则应考虑永久运行并在某些情况下清理或停止调用。
var doSomethingOnceValueIsPresent = function () {
    if ($('#current').val() != '')
    {
        alert('something!');
    }
    else
    {
        setTimeout(function(){
            doSomethingOnceValueIsPresent()
            }, 2000);
    }
};

doSomethingOnceValueIsPresent();

0
如果您能将 <span> 更改为 <input>,您就可以使用 jQuery 的 .change() 事件,这将使您的生活更加轻松。
<input id="current" value="" type="hidden" />

JS

$('#current').change(function(e){
    myFunction();
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接