我有这些号码<a href />
HTML 页面中的链接:
<a ...>
<a ...>
.....
<a ...>
我想要的是在单击每个链接时我必须在同一 html 页面上显示一个文本文件。
文本文件可以显示在textarea
中或iframe
.
我怎样才能做到这一点?
......编辑............ 正确的代码
<html>
<head>
<title>Ajax Test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$("a").click(function(e){
e.preventDefault();
$.get( $(this).attr("href") ).done(function(e){
$("textarea").html(e);
});
});
});
</script>
</head>
<body>
<a href="{{STATIC_URL }}foo.txt">foo bar</a><br>
<textarea></textarea>
</body>
</html>
最佳答案
您可以使用AJAX从服务器获取文本文件数据,然后将其放入文本字段。
演示:http://jsfiddle.net/DerekL/63BLB/
$("a").click(function(e){ //select all <a>
e.preventDefault(); //remove default link effect
$.get( $(this).attr("href") ) /*AJAX (using jQuery)..
..and insert the URL of text file*/
.done(function(e){ //When it is downloaded,
$("textarea").html(e); //shows it in <textarea>
});
});
如果您是 jQuery 新手,您可能需要查看 their documentation ,特别是$.ajax
。 :)
注意:您只能获取 same origin 中的文本文件.
注2:上面的代码是使用jQuery 编写的。如果您不想使用 jQuery,则必须执行 the whole native new XMLHttpRequest
thing .
关于javascript - 在 HTML 中的超链接事件上显示文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19964986/