JavaScript函数仅在元素存在时返回

时间:2017-04-22 11:59:24

标签: javascript

我正在开发一个需要动态页面加载的项目,并且还需要在页面加载后返回该函数。因为它等待页面的某些部分加载,然后才能执行其他任何操作。

目前我正在使用MutationObservers来检测元素何时出现。可悲的是,这不能让我知道我的整体功能,以回归真实的'一旦找到元素。

我正在使用这个代码,经过大量的查看后,当我检查元素是否存在时,我需要的是什么。但就像我说的那样,他不会返回一个值。

//
//MutationObserver Function : Allows for dynamic page watching without interrupting loading
(function(win) {
    'use strict';
    var listeners = [],
    doc = win.document,
    MutationObserver = win.MutationObserver || win.WebKitMutationObserver,
    observer;
    function ready(selector, fn) {
        // Store the selector and callback to be monitored
        listeners.push({
            selector: selector,
            fn: fn
        });
        if (!observer) {
            // Watch for changes in the document
            observer = new MutationObserver(check);
            observer.observe(doc.documentElement, {
                childList: true,
                subtree: true
            });
        }
        // Check if the element is currently in the DOM
        check();
    }
    function check() {
        // Check the DOM for elements matching a stored selector
        for (var i = 0, len = listeners.length, listener, elements; i < len; i++) {
            listener = listeners[i];
            // Query for elements matching the specified selector
            elements = doc.querySelectorAll(listener.selector);
            for (var j = 0, jLen = elements.length, element; j < jLen; j++) {
                element = elements[j];
                // Make sure the callback isn't invoked with the
                // same element more than once
                if (!element.ready) {
                    element.ready = true;
                    // Invoke the callback with the element
                    listener.fn.call(element, element);
                }
            }
        }
    }
    // Expose `ready`
    win.ready = ready;
})(this);

然后我打电话但很明显,即使公司名称没有填写,这个功能也会返回。如何让这个功能等到公司名称填写完毕后才能返回

function fillOutInitial(){

ready("input[id='companyName']", function(element) {
  document.getElementById('companyName').value = "COMPANY NAME";});


return "companyName Completed"
}

1 个答案:

答案 0 :(得分:1)

Zach要求回调和承诺示例。您将在1秒后收到警报,指示存在第一个companyName输入,并且已设置该值。您将在2秒后收到一条警告,表示companyName2输入存在且已设置。

&#13;
&#13;
//SAMPLE WAITING FOR INPUTS
window.setTimeout(function () {
	document.getElementById("myDiv").innerHTML = '<input id="companyName" />'
}, 1000);
window.setTimeout(function () {
	document.getElementById("myDiv").innerHTML = '<input id="companyName2" />'
}, 2000);



//MutationObserver Function : Allows for dynamic page watching without interrupting loading
(function(win) {
    'use strict';
    var listeners = [],
    doc = win.document,
    MutationObserver = win.MutationObserver || win.WebKitMutationObserver,
    observer;
    function ready(selector, fn) {
        // Store the selector and callback to be monitored
        listeners.push({
            selector: selector,
            fn: fn
        });
        if (!observer) {
            // Watch for changes in the document
            observer = new MutationObserver(check);
            observer.observe(doc.documentElement, {
                childList: true,
                subtree: true
            });
        }
        // Check if the element is currently in the DOM
        check();
    }
    function check() {
        // Check the DOM for elements matching a stored selector
        for (var i = 0, len = listeners.length, listener, elements; i < len; i++) {
            listener = listeners[i];
            // Query for elements matching the specified selector
            elements = doc.querySelectorAll(listener.selector);
            for (var j = 0, jLen = elements.length, element; j < jLen; j++) {
                element = elements[j];
                // Make sure the callback isn't invoked with the
                // same element more than once
                if (!element.ready) {
                    element.ready = true;
                    // Invoke the callback with the element
                    listener.fn.call(element, element);
                }
            }
        }
    }
    // Expose `ready`
    win.ready = ready;
})(this);


//CALLBACKS
fillOutInitialCallback(function (someValue) {
  //Wont be called until after companyName has been set.
  alert(someValue)
});

function fillOutInitialCallback(fnCallback){
  ready("input[id='companyName']", function(element) {
    document.getElementById('companyName').value = "COMPANY NAME";
    fnCallback("companyName has been set.")
  });  
}

  
  
//PROMISES
fillOutInitialPromise().then((someValue) => {
  //Wont be called until companyName2 has been set.
  alert(someValue);
});

function fillOutInitialPromise(){
  return new Promise((resolve, reject) => {
    ready("input[id='companyName2']", function(element) {
      document.getElementById('companyName2').value = "COMPANY NAME";
      resolve("companyName2 has been set");
    });      
  });  
}
  
  
  
  
&#13;
<div id="myDiv">

</div>
&#13;
&#13;
&#13;