我有一个关于 jquery click to load url in a div using id 的问题。
我正在尝试,当用户单击 class="open"id="1"
时,ajax URL 将仅打开 id="openpage1"
但代码显示总而言之,我在这里做错了什么,有人可以在这方面帮助我吗?
$.base_url = 'http://localhost/';
$(".open").on('click', function() {
var ID = $(this).attr("id");
$("#openpage" + ID).slideToggle('fast');
var URL = $.base_url + 'page.php';
$.ajax({
type: "POST",
url: URL,
cache: false,
success: function(html) {
if (html) {
$(".page_area").html(html);
}
}
});
return false;
});
HTML
<!--First Post Started-->
<div class="post_area" id="1">
<div class="open" id="1">Click for 1</div>
<div class="opened_page" id="openpage1">
When user click (class=open id 1 then ajax page will need to open just here)
</div>
</div>
<!--First Post finished-->
<!--Second post started-->
<div class="post_area" id="2">
<div class="open" id="2">Click for 2</div>
<div class="opened_page" id="openpage2">
When user click (class=open id 2 then ajax page will need to open just here)
</div>
</div>
<!--Second Post finished-->
最佳答案
我看到 3 个问题
- 我强烈建议使用唯一的非数字 ID - 但我的代码不再需要 ID - 我使用 datza-id 来保存链接的信息
- 您需要找到最近的已打开页面 - 您尝试 HTML 中没有的 page_area
- 我会缓存点击的对象以在成功时使用
像这样:
<div class="post_area">
<div class="open" data-id="1">Click to open</div>
<div class="opened_page">
When user click (class=open id 1 then ajax page will need to open just here)
</div>
</div>
使用
$(function() {
$(".open").on('click', function(e) {
e.preventDefault(); // in chase you change to a link or button
var $this = $(this),
URL = $.base_url + 'page.php?page='+$this.data("id"),
$page = $this.next("opened_page"); // sibling
$.ajax({
type: "POST",
url: URL,
cache: false,
success: function(html) {
if (html) {
$page.html(html).slideToggle('fast');; // sibling
}
}
});
});
});
关于javascript - Jquery Ajax 单击在 div 中显示页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32451289/