如何将鼠标悬停在链接上时显示demo_test.txt的内容?我哪里出错了,我的代码应该是什么样子

How can I display the contents of demo_test.txt when I hover over a link? Where am I going wrong, and how should my code look?

本文关键字:出错 错了 我的 什么样 代码 链接 悬停 鼠标 txt test 显示      更新时间:2023-09-26

我哪里出错了,我的代码应该是什么样子?

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
<script>
 $(".button").hover(function(){ $.ajax({url:"demo_test.txt", success:function(result){ $("#div1").html(result); }}); }); 
</script>
</head>
<body>
 <div id="div1"><a href="#" class="button">Hover me</a></div> 
</body>
</html>

事件侦听器未初始化。要么将悬停侦听器包装在 $(document).ready 中,要么将 javascript 放在 DOM 中.button之后:

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
<script>
$(document).ready(function(){
   $(".button").hover(function(){ $.ajax({url:"demo_test.txt", success:function(result){ $("#div1").html(result); }}); }); 
});
</script>
</head>
<body>
   <div id="div1"><a href="#" class="button">Hover me</a></div> 
</body>
</html>

请参阅:http://api.jquery.com/ready/

传递给 .ready() 的处理程序保证在 DOM 已准备就绪,因此这通常是附加所有其他内容的最佳位置 事件处理程序并运行其他 jQuery 代码。

ajax 请求应指向后端代码中的控制器操作方法。 在那里进行处理以读取文件并将其作为字符串返回,以便根据需要在客户端进行操作。

$.ajax({
        cache: true,
        type: 'post',
        async: false,
        url: '/SomeAction/GetText',
        success: function (msg) {
           // do your replace here
        }
    });
});