【发布时间】:2016-03-28 16:20:41
【问题描述】:
我有一个链接如下:
<a id="link" href="hospitaldetails.php?id=1">Click Here</a>
点击链接将使用 Ajax 更新同一页面上的 div:
<!--Div containing ajax response of hospital details-->
<div id="container"></div>
jQuery ajax 脚本如下:
<script type="text/javascript">
//getting details of hospital through ajax request and displayed on <div> with id container
$("#link").click(function(e) {
e.preventDefault(); // <-------stop the default behavior here.
var id = this.href.split('=').pop(); // extract the id here
$.ajax({
type: "get",
url: "hospitaldetails.php",
data: {id:id}, // now pass it here
success: function(data) {
$('#container').html(data);
}
});
});
</script>
除了页面上有多个不同 id 的链接之外,一切正常:
href="hospitaldetails.php?id=1"
href="hospitaldetails.php?id=2"
单击第一个链接将正确更新容器 div,但第二个链接将在新窗口中打开,URL 为 hospitaldetails.php?id=2。
为什么不使用新 id 的内容更新同一个 div ?上面的代码有什么问题??
【问题讨论】:
-
你能举例说明你是如何设置第二个 div 的吗?您是否使用具有相同 id="link" 的 div?假设是这样,您需要将其设为一个类,因为页面上应该只有一个具有给定 ID 的元素。我想将其更改为一个类并定位该类应该可以解决您的问题。
-
使用类,id需要唯一