当我点击多个链接时,我有一张图片发生了变化。以下 javascript 代码运行良好:
<img src="myImage.png" id="mainImg" />
<a href="javascript:;" id="report1_id" onclick="document.getElementById('mainImg').src='http://localhost/convertToReport1.do';">Report1</a>
<a href="javascript:;" id="report2_id" onclick="document.getElementById('mainImg').src='http://localhost/convertToReport2.do';">Report2</a>
但我正在尝试更改代码以改为使用 Jquery 代码。它调用与 javascript 示例相同的服务器代码。不会生成任何错误,并且会返回一个 png。但是图像不会在 html 页面上更新。更糟糕的是,html 会移动到页面顶部。在工作的 javascript 代码中,图像会焕然一新,并带有一种漂亮的 Ajaxy 感觉,其中只有图像会发生变化,而页面的其余部分不会移动。我的 Jquery 代码如下:
<img src="myImage.png" id="mainImg" />
<a href="" id="report1_id">Report1</a>
<a href="" id="report2_id">Report2</a>
<script type="text/javascript">
$(document).ready(function(e) {
$("#report1_id").click(function(e) {
alert("This Is Report1");
d = new Date();
$("#mainImg").attr("src", "http://localhost/convertToReport1.do?"+d.getTime());
});
$("#report2_id").click(function(e) {
alert("This Is Report2");
d = new Date();
$("#mainImg").attr("src", "http://localhost/convertToReport2.do?"+d.getTime());
});
});
</script>
谁能看出我做错了什么?任何帮助,将不胜感激。
最佳答案
根据您的代码,图像 src 应该更改,但它可能不会更改为您想要的。确保 http://localhost/convertToReport1.do
准确返回您需要的内容(理想情况下,您可以在问题本身中指定)。
页面跳转是因为anchors的href属性。要么删除它,要么阻止点击处理函数中的默认 anchor 行为,如下所示:
$("#report1_id").click(function(e) {
e.preventDefault(); // <--- this is the key, return false would also work at the end
alert("This Is Report1");
d = new Date();
$("#mainImg").attr("src", "http://localhost/convertToReport1.do?"+d.getTime());
});
在此处查看实际效果:http://jsfiddle.net/egvac61c/
关于Jquery 代码的 Javascript 代码不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26329752/