![](/img/trans.png)
[英]Can I get usable data in a jQuery live handler for a custom event?
[英]results of jquery $.get assignment to variable not usable in event listener
任何人都可以識別此代碼中的問題和/或幫助解決它嗎?
我正在嘗試預加載html文件,將其html分配給變量,然后在用戶單擊按鈕后將它們注入div。
我可以在單擊時將html文件加載到div的地方成功運行,但是我想預加載html,這樣用戶就不必等待html文件的外部資源加載,如果有互聯網也可以不加載故障/外部資源獲取問題。
在代碼中,警報成功顯示了html,因此我至少知道該部分有效。
//IIFE
(function() {
// ^other stuff omitted
// start navButton behavior
var hatContent;
function doSomethingWithData(data) {
hatContent = data;
alert(data);
}
$.get('helpAndTips.html', doSomethingWithData);
function replaceNotebookContentWithVariable(content){
$("#usersNotebook").innerHTML = content;
}
document.getElementById('helpAndTipsButton').addEventListener("click", function(){
replaceNotebookContentWithVariable(hatContent);
}, false);
// end navButton behavior ____________________X
// other stuff omitted
})(); // end IIFE
嘗試一下,看看它是否更適合您。
(function() { //save the ajax deferred var helpAndTips = $.get('helpAndTips.html'); function replaceNotebookContentWithVariable(content) { $("#usersNotebook").innerHTML = content; } $('#helpAndTipsButton').on("click", function() { //call the replace with the result of the deferred whenever it gets it //if the deferred has already resolved this will happen immediately helpAndTips.then(function(hatContent) { replaceNotebookContentWithVariable(hatContent); }); }, false); })();
由於某種原因$('#usersNotebook').innerHTML = data;
不起作用,但是document.getElementById('usersNotebook').innerHTML
起作用。
我從來沒有真正像變量一樣使用過helpAndTips,我認為這是因為獲取事件數據的執行順序比事件使用順序要晚。 但是@Taplar關於使用jquery的.then在數據獲取后觸發函數的建議允許我在“完成”函數內部添加“ on cick”事件偵聽器以及獲取的數據,以確保數據的可用性。放置在事件鏈中。 因此以下代碼對我有用。 謝謝!
`// start navButton behavior
function replaceNotebookContentWithVariable(content) {
document.getElementById('usersNotebook').innerHTML = content;
}
var helpAndTips = $.get('helpAndTips.html');
helpAndTips.then(function(data){
document.getElementById('helpAndTipsButton').addEventListener("click", function(){
replaceNotebookContentWithVariable(data);
}, false);
})
// end navButton behavior ____________________X`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.