jQuery等待元素属性具有值

Flo*_*Flo 4 jquery wait

我有一个元素

<span id="current" data=""></span>
Run Code Online (Sandbox Code Playgroud)

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();
    }
Run Code Online (Sandbox Code Playgroud)

我想执行另一个函数,但在该函数中我想等到属性data不等于空。我正在检查这个:http : //javascriptisawesome.blogspot.com/2011/07/faster-than-jquerydocumentready-wait.html 但我更喜欢用默认的 jQuery 来做这个。

我怎么能这样做?

neo*_*r99 8

您可以轮询数据的价值:

function check() {
    if (!$('#current').attr('data')) {
        return setTimeout(check, 1000);
    }

    // do work here
}

check();
Run Code Online (Sandbox Code Playgroud)


Tom*_*now 0

如果您能够将 更改<span>为 an,<input>您将能够使用 jQuery 的.change()事件,这将使您的生活变得更加轻松。

<input id="current" value="" type="hidden" />
Run Code Online (Sandbox Code Playgroud)

JS

$('#current').change(function(e){
    myFunction();
});
Run Code Online (Sandbox Code Playgroud)