【问题标题】:Loading Text File into Div Using Jquery使用 Jquery 将文本文件加载到 Div
【发布时间】:2012-12-27 20:42:51
【问题描述】:

我创建了这个脚本:

  <script>function txtload () {$(".divbody").load("maintxt/information1.txt");}</script>

我正在使用这样的链接:

<a href="#" onclick="ChangeImage(), txtload ()">Information 1</a>

我需要更改脚本以创建多个 href 为每个链接加载不同的文本:

<a href="#" onclick="ChangeImage(), txtload ()">Information 1</a>
<a href="#" onclick="ChangeImage(), txtload ()">Information 2</a>
<a href="#" onclick="ChangeImage(), txtload ()">Information 3</a>
<a href="#" onclick="ChangeImage(), txtload ()">Information 4</a>

你能帮忙吗?我尝试从脚本中删除“”并将其放在 href 本身中...不知道我在做什么...

认为这应该可行。请给我你的意见:

<script>function txtload () {$(".divbody").load("maintxt/" + filename);}</script>

<a href="#" onclick="ChangeImage(), txtload ("information1.txt")">Information 1</a>

谢谢!

【问题讨论】:

    标签: jquery text hyperlink


    【解决方案1】:

    你可以使用参数

    <script>
        function txtload ( url ) {
            $(".divbody").load( url );
        }
    </script>
    

    然后在你的 html 中:

    <a href="#" onclick="txtload('url to your text file')">Information 1</a>
    

    或者如果你真的想在你的 href 中使用它:

    <a href="your url" onclick="txtload(this.href); return false;">Information 1</a>
    

    在你的代码中还有一个函数ChangeImage,你没有在任何地方解释过。我只是在我的示例中忽略了它。

    实际上更好的另一种方法是这个脚本:

    $("a.some_class_for_these_links").on("click", function (e) {
        e.preventDefault();
        $(".divbody").load( this.href );
    });
    

    然后是这个html

    <a href="your url" class="some_class_for_these_links">Information 1</a>
    

    【讨论】:

      【解决方案2】:

      如果你打算使用 jQuery,那么在 onclick 中使用内联脚本是没有意义的;

      给链接一个通用类,您可以使用href 分配您要加载的文件。

      <a href="maintxt/information1.txt" class="load_link">Information 1</a>
      

      然后在 jQuery 中:

      $(function(){
      
         $('.load_link').click(function(){
             ChangeImage();
             /* "this" is actual link clicked*/
             $(".divbody").load(this.href);
              /* prevent browser opening new page*/
              return false;
      
        })
      })
      

      如果用户禁用了 javascript,他们仍然可以访问数据,因为它位于 href 中,单击链接将允许他们查看文本文件。搜索引擎机器人也是如此

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-09
        • 2021-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多