正在加载包含文件内容的文本区域

Loading textarea with contents from file

本文关键字:文本 区域 文件 加载 包含      更新时间:2023-09-26

问题

我的目标是能够将文本文档中的文本加载到<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...

有几件事。。。

CCD_ 3正在立即调用CCD_。您可以通过省略()来传递函数,但您只是在调用它

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
}