我想使用javascript filereader()从另一个页面加载另一个页面,如何根据div指定函数的参数?
html代码:
<!DOCTYPE HTML>
<html>
<body>
<div class='try1' onclick="openFile('test1.txt')">Show Test1</div>
<div class='try2' onclick="openFile('test2.txt')">Show Test2</div>
<div id='show_content'></div>
<script>
var openFile = function(event) {
var input = event;
var reader = new FileReader();
reader.onload = function(){
var text = reader.result;
document.getElementById("show_content").innerHTML = (reader.result.substring(0, 200));
};
reader.readAsText(input.files[0]);
};
</script>
</body>
</html>我想要它,这样当:
1)我单击div class='try1',它会将一个名为'test1.txt‘的文件加载到div id='show_content’中,
2)当我点击div class='try2‘时,它会将一个名为'test2.txt’的文件加载到div id='show_content‘中。
我该如何实现这一点?我知道我可以使用jQuery .load()函数,但事实证明jQuery .load()函数需要一个服务器并使用xmlhttprequest进行加载,而我需要在本地执行此操作。如果有任何更好的解决方案来实现这一点,我们将非常感谢所有的答案。Thx
发布于 2015-05-22 18:28:18
您可以在页面中放置一个隐藏的input,然后显式调用openFile;
<div id='try1' onclick="openFile('test.txt')">show try 1</div>
<div id="show_content"></div>
<input type="file" id="fileElem" accept="text/plain" style="display:none" onchange="openFile(event)">您只需将事件侦听器添加到div中
var try1 = document.getElementById("try1"),
fileElem = document.getElementById("fileElem");
try1.addEventListener("click", function (e) {
if (fileElem) {
fileElem.click();
}
e.preventDefault(); // prevent navigation to "#"
}, false);最后:
var openFile = function (event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function () {
var text = reader.result;
var content = document.getElementById("show_content");
content.innerHTML = reader.result.substring(0, 200);
};
reader.readAsText(input.files[0]);
};发布于 2015-05-22 14:59:19
你可以用jquery做到这一点,我已经在本地做到了这一点,没有任何服务器。
对于第一个,试试这个:
$(".try1").click(function () {
$("#show_content").load("text1.txt", function (responseTxt, statusTxt, xhr) {
if (statusTxt == "success")
{
//alert("External content loaded successfully!");
}
if (statusTxt == "error")
{
//alert("Error: " + xhr.status + ": " + xhr.statusText);
}
});
});对于第二个:
$(".try2").click(function () {
$("#show_content").load("text2.txt", function (responseTxt, statusTxt, xhr) {
if (statusTxt == "success")
{
//alert("External content loaded successfully!");
}
if (statusTxt == "error")
{
//alert("Error: " + xhr.status + ": " + xhr.statusText);
}
});
});https://stackoverflow.com/questions/30389757
复制相似问题