javascript - 在 HTML 中的超链接事件上显示文本文件

标签 javascript html

我有这些号码<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/

相关文章:

javascript - 当我单击元素数学/物理/化学时如何使用 jquery 获取跨度 ID

html - 从元素中删除截断样式

javascript - 按数字顺序拖动选定的输入框

javascript - 将 SVG' 缩放到宽度和高度

html - 如何有条件地否定段落标签上的文本缩进

html - 在 IE 中设置 Render Field

javascript - 如何在 chrome 中使用 jquery.load() 在 html 中嵌入文件

javascript - 如何根据下拉选择更改跨度的内容

javascript - 在另一个框架中显示 div

javascript - 在 Angular8 中将 HTTP 响应 json 转换为 typescript 对象