jQuery 等待元素属性有值

标签 jquery wait

我有一个元素

<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/

相关文章:

c - 进程ID,waitpid

Java等待通知死锁问题

jquery - 用于 j2ee 应用程序的可编辑 Java 语法荧光笔

jquery - 触摸友好的工具提示

jQuery 流沙 : CSS applied after JS load causes jerky behaviour

javascript - Jquery .toggle .animate

c - 如何使用信号量让 n 个进程等待?

Java线程: Wait Notify mechanism with ArrayList

javascript - 当选项更改并且我需要重新加载页面时,如何保持该选项处于选中状态?

Python 子进程等待任何先完成的子进程