如何检测document.write()是否发生在JavaScript中?

时间:2010-10-19 19:41:13

标签: javascript

我希望在成功发生2个document.write()语句时执行某些操作。我尝试了以下但是没有用:

        function loadFields() {
            var load1 = document.write("<input type='text' name='StoreLocation' value='"+storeLocation+"' />");
            var load2 = document.write("<input type='text' name='couponType' value='"+couponType+"' />");
        }

        if (loadFields()) {
            alert('both items have loaded.');
        }

我也尝试了这个和同样的结果:

        var load1 = document.write("<input type='text' name='StoreLocation' value='"+storeLocation+"' />");
        var load2 = document.write("<input type='text' name='couponType' value='"+couponType+"' />");

        if (load1 && load2) {
            alert('both items have loaded.');
        }

3 个答案:

答案 0 :(得分:3)

    function loadFields() {
        document.write("<input type='text' name='StoreLocation' value='"+storeLocation+"' />");
        document.write("<input type='text' name='couponType' value='"+couponType+"' />");
        return true;
    }

    if (loadFields()) {
        alert('both items have loaded.');
    }

OR

    function loadFields() {
        document.write("<input id='StoreLocation' type='text' name='StoreLocation' value='"+storeLocation+"' />");
        document.write("<input id='cuponType' type='text' name='couponType' value='"+couponType+"' />");
    }

    if (document.getElementById("StoreLocation") && document.getElementById("cuponType")) {
        alert('both items have loaded.');
    }

答案 1 :(得分:3)

你要做的事没有意义。遇到代码后会立即发生document.write,因此在document.write之后的下一行,文本已经添加到文档中。

答案 2 :(得分:0)

document.write调用不是异步的,这意味着它们在执行后面的任何代码时都会发生。

// It has not happen yet as of this point.
var load1 = document.write("<input type='text' name='StoreLocation' value='"+storeLocation+"' />");
var load2 = document.write("<input type='text' name='couponType' value='"+couponType+"' />");
// Now it has happen, as of this point.