jQuery没有将文本内容加载到div元素中

时间:2014-02-22 06:32:28

标签: javascript jquery html text load

我有这个脚本。就像我想的那样简单。

<script type="text/javascript">
        $(document).ready(function () {
            $("a.textlink").click(function () {
                $("#WritingContent").load(this.attr("href"))  
            });
        });
</script>

和这个链接:

<a href="Writings/test.txt" class="textlink">test</a>(还有一堆其他类似的链接)

假设将文本文件内容加载到指定的div中是不是?当我点击该链接时,所有发生的事情就是打开文本文件。它不会将其加载到div中。

这里真正发生的是我有一大堆未格式化的.txt文件,我想做以下事情:

  • <h2>代码
  • 中的第一行换行
  • 将每个后续段落打包在<p>标记
  • 将结果输出到#WritingContent div

仍然是jQuery的新手。无法研究解决方案。

1 个答案:

答案 0 :(得分:0)

我注意到您的代码中有两个问题。如评论中所述,单击链接将打开该链接。

正如Adil提到的答案之一,您可以使用JQuery attr访问链接的href

$("#loadText").attr("href");

或DOM attr

var a = document.getElementById("loadText"); 
a.href;

其次,为防止页面打开文件/重定向到文件,一种方法是更改​​链接的href属性,并将实际文件地址添加到您自己选择的其他属性中。

//now href will not redirect your page to anywhere, it will just append some text to the url.    
<a href="#loadText" addref="Writings/test.txt" class="textlink">test</a>

$(document).ready(function () {
    $("a.textlink").click(function () {
        $("#WritingContent").load($(this).attr("addref")) //accessing addref instead of href
    });
});

另一种方法是保持链接与原始href一样,但防止在链接点击时重定向/打开文件

 $(document).ready(function () {
    $("a.textlink").click(function (e) {
         e.preventDefault();//here we prevent the link from doing it's what it was meant to do, linking! 
        $("#WritingContent").load($(this).attr("href"))  
    });
});