簡體   English   中英

使用文件中的內容加載textarea

[英]Loading textarea with contents from file

問題

我的目標是能夠將文本從文本文檔加載到<textarea> ,以便在屏幕上顯示給用戶。 $ .get()調用能夠檢索內容並且似乎將它們存儲在'notes'全局變量中,但是當調用.val()並傳遞給'notes'時,它似乎不是加載要在<textarea>顯示的字符串。

我已經閱讀了關於Stackoverflow和谷歌上其他文章的幾個問題,但到目前為止我還沒有找到任何解決方案。 有沒有人有什么建議?

HTML

<div class="col-md-5 module">
   <h1>My Notes</h1>
   <form>
      <textarea id="note-app" class="full-width full-height" placeholder="Save your notes here..."></textarea>
   </form>
</div>

notes.js

var notes = "pie";

$.get("../docs/notes.txt", function (data) {
    console.log('Loading notes...');
    notes = data;
});


function loadNotes(data) {
    console.log('Data:\n{\n'+data+'\n}\n');
    $("#note-app").val(data);
}

$( document ).ready(loadNotes(notes));

產量

notes.js:14
Data:
{
pie
}

jquery.min.js:4 XHR finished loading: GET
"http://localhost:63342/Dad/docs/notes.txt".k.cors.a.crossDomain.send @
jquery.min.js:4n.extend.ajax @ jquery.min.js:4n.(anonymous function) @
jquery.min.js:4(anonymous function) @ notes.js:7
notes.js:8 Loading notes...

幾件事......

$( document ).ready(loadNotes(notes)); 正在調用loadNotes而不是等待文檔准備好。 您可以通過省略()傳遞函數 - 但您只是調用它。

loadNotes被觸發時,您的$.get調用仍有可能繼續運行。 使用回調 - 等待完成 - 然后運行loadNotes

重構:

function getNotes(callback) {
    $.get("../docs/notes.txt", function (data) {
        console.log('Loading notes...');
        callback(data);
    });
}

function loadNotes() {
    getNotes(function(notes) {
        $("#note-app").val(notes);
    });
}

$(document).ready(loadNotes);

$( document ).ready(loadNotes(notes));

應該

$( document ).ready(function() { loadNotes(notes) });

ready() jQuery函數接受一個函數。 你正在做的是在讀取那行代碼時正確執行該函數。 不是在實際加載文檔時。

如果能為您解決問題,請告訴我。

為什么不把$.get放在文件准備好的內部? 通過您顯示的代碼將其存儲在變量中是沒有意義的。 (如果您想要實現的唯一事情是在加載文檔后獲取內容)

$( document ).ready(function() {

    $.get("../docs/notes.txt", function (data) {
        $("#note-app").val(data);
    });

));

或作為一種功能:

$( document ).ready(function() {

    function loadNotes() {
        $.get("../docs/notes.txt", function (data) {
            $("#note-app").val(data);
        });
   }

   loadNotes(); //Execute function now when DOM is loaded

));

值得一提的另一件事是

var notes = "pie"; 在您的示例中,文檔已准備就緒,因此無法在文檔就緒時訪問。

var notes = 'pie';
$( document ).ready(function() {
    alert(notes); //will alert undefined or similar
    var notes = 'die';
    alert(notes); //will alert die
}

如果你想要一個像這樣的全局變量你應該使用:window.notes =“pie”;

var window.notes = 'pie';
$( document ).ready(function() {
    alert(notes); //will alert pie
    var notes = 'die';
    alert(notes); //will alert die
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM