2017-06-03 2 views
2

を続行する前にDOM要素内の特定のテキストを待ち?それはイベントループを遮断する)私はそれが値を返す前に変更するためにいくつかのテキストを待つべき機能を持っている

+0

rx.js、観察はあなたの親友です。またはEventEmitter – Val

+0

私はそう思います。 whileループはページをフリーズします。 setIntervalを使用して、テキストが変更されたかどうかを確認できます。 – vabii

+0

その要素のchangeイベントにリスナーを置くことができませんでしたし、 'getElementText'をコールバックとしてあなたの条件を満たすときに値で呼び出すことができませんでしたか? – ken4z

答えて

1

jQueryのまたは任意の他の外部ライブラリの不要を、あなたは単にMutationObserverを使用することができます。https://developer.mozilla.org/en/docs/Web/API/MutationObserverここ

簡単な例は、あなたがタイプcharacterDataの通知を持っていますとき、あなたをテキストの変更(私の例では5秒後):

// select the target node 
 
var target = document.getElementById('some-id'); 
 
    
 
// create an observer instance 
 
var observer = new MutationObserver(function(mutations) { 
 
    mutations.forEach(function(mutation) { 
 
    console.log(mutation.type); 
 
    });  
 
}); 
 
    
 
// configuration of the observer: 
 
var config = { attributes: true, childList: true, characterData: true, attributes: true, subtree: true }; 
 
    
 
// pass in the target node, as well as the observer options 
 
observer.observe(target, config); 
 
    
 
// later, you can stop observing 
 
//observer.disconnect(); 
 
setTimeout(function() { 
 
\t target.innerText = 'Changed text!'; 
 
}, 5000);
<div id="some-id"> 
 
    AAA 
 
</div>

観察者の設定から変更内容

+0

注:これはIE <11では機能しません –

0

DOMSubtreeModifiedイベントのためにスパイする必要はありませんすべてのプロパティを削除します要素が変更されたときにトリガーされるので、それを使ってテキストがロードされているかどうかを検出できます。

コールバック関数を使用して、ロード時に値を返すことができます。それとももっと良い:(jQuery)約束!

var element = document.getElementById('element'); 
 

 
function isLoading() { 
 
    return element.innerText.indexOf('Loading') >= 0; 
 
} 
 

 
function getElementText() { 
 
    var def = $.Deferred(); 
 

 
    if (!isLoading()) { 
 
     def.resolve(element.innerText); 
 
     return def.promise(); 
 
    } 
 

 
    $(element).on('DOMSubtreeModified', function() { 
 
     if (!isLoading()) { 
 
      def.resolve(element.innerText); 
 
     } 
 
    }); 
 

 
    return def.promise(); 
 
} 
 

 
getElementText().then(function (text) { 
 
    // Text is loaded! 
 
    alert(text); 
 
}); 
 

 
// Load text after 3 seconds for demonstration 
 
setTimeout(function() { 
 
    element.innerText = 'Changed!'; 
 
}, 3000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div id="element">Loading</div>

1

rxjsとエレガントな方法:

var source = document.getElementById('source'); 
 
var target = document.getElementById('target'); 
 

 
Rx.Observable.fromEvent(source, 'keyup') 
 
    .filter((e) => e.target.value === 'Admin') 
 
    .subscribe(() => target.innerText = "Matched.");
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.0/Rx.min.js"></script> 
 

 
<input id="source" /> <strong>input 'Admin' to trigger</strong> 
 
<p id="target">Not match.</p>

関連する問題