简体   繁体   English

jQuery Ajax单击div中的显示页面

[英]Jquery Ajax click show page in a div

I have one question about jquery click to load url in a div using id. 我有一个关于jquery点击以使用id在div中加载url的问题。

I am trying when user clicking the class="open" id="1" then the ajax URL will open just id="openpage1" but the code showing in all id="openpageXX" what i am doing wrong here anyone can help me in this regard ? 我正在尝试当用户单击class="open" id="1" ,ajax URL将仅打开id="openpage1"但是所有id="openpageXX"显示的代码我在做什么错了,这里有人可以帮助我在这方面 ?

$.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 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-->

I see 3 issues 我看到3个问题

  1. I strongly suggest using unique non-numeric IDs - but my code no longer needs ID - I use datza-id to hold the information for the link 我强烈建议使用唯一的非数字ID-但我的代码不再需要ID-我使用datza-id来保存链接的信息
  2. you need to find the closest opened_page - you try page_area which is not in your HTML 您需要找到最近的open_page-您尝试不在HTML中的page_area
  3. I would cache the clicked object to use in the success 我将缓存单击的对象以成功使用

like this: 像这样:

<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>

using 使用

$(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
         }
       }
    });
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM