我有一个脚本,可以按顺序将网址放入一个 iframe 中:
<script type="text/javascript">
$(document).ready(function(){
var array = ['http://www.example1.come', 'http://www.example2.com', 'http://www.example3.com'];
var beforeLoad = (new Date()).getTime();
var loadTimes = [];
$('#1').on('load', function() {
loadTimes.push((new Date()).getTime());
$('#1').attr('src', array.pop());
if (array.length === 0) {
$.each(loadTimes, function(index, value) {
$("#loadingtime"+index).html(value - beforeLoad);
});
}
}).attr('src', array.pop());
});
</script>
我得到了一个带有 url 列表的 txt 文件。该文件中的 url 写入一列(1 列,每个 url 从新行开始)。如何用该 txt 文件的内容替换 javascript 中的“var 数组”?
最佳答案
这是基本要点,在我放置注释的位置检索文件后,您需要嵌入您想要运行的任何代码。
$.get("your_url",
function(data) {
var array = data.split(/\r\n|\r|\n/) //regex to split on line ending
var beforeLoad = (new Date()).getTime();
var loadTimes = [];
//.... rest of your code here
}
);
请注意,如果文件不存在,这不会执行任何错误处理,并且您可能需要重写它以使用 jQuery's "Promise" interface described here.
关于javascript - 将txt文件数据读取到javascript数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15055940/