简体   繁体   English

使用Ajax返回加载的内容时功能不起作用

[英]Features not working when returning to loaded content with Ajax

I have a question regarding Ajax, which I am using for the first time. 我有一个关于Ajax的问题​​,这是我第一次使用。 My project consists of a menu with links to the different sections of the site. 我的项目包含一个菜单,该菜单包含指向网站不同部分的链接。 On the main page there is the simplest photo viewer, with two clickable icons to navigate through the pictures. 主页上是最简单的照片查看器,带有两个可单击的图标,可浏览图片。 Then, when the user clicks on the different links, ajax displays the different sections: contact, gallery, contact, etc... 然后,当用户单击不同的链接时,ajax将显示不同的部分:联系人,图库,联系人等。

My problem is that when one clicks back on the "home" button and is confronted with the photo viewer, the clickable icons no longer let you browse through the pictures. 我的问题是,当人们单击“主页”按钮并面对照片查看器时,可单击的图标不再允许您浏览图片。 As I don't have any experience with Ajax, I am not too sure why this is. 由于我没有使用Ajax的经验,因此我不太确定为什么会这样。 The javascript only works the first time you are presented with the photo viewer as you load the site, but doesn't seem to be read once the content is loaded again with ajax. javascript仅在您加载网站时第一次向您显示照片查看器时有效,但是一旦使用ajax再次加载内容,似乎就无法读取。

Here is the code: 这是代码:

index.html index.html

<!DOCTYPE html>
<html lang="en-US">

    <head>

        <meta charset="UTF-8">
        <title>Photography</title>
        <link rel="stylesheet" type="text/css" href="styles.css">

    </head>

    <body>

    <div id="header">
      <div id="title"><h1>TITLE<span id="subtitle">SUBTITLE</span></h1></div>
          <nav class="cf" id="menu">
          <ul>
            <li><a href="about.html">ABOUT</a></li>
            <li><a href="gallery.html">GALLERY</a></li>
            <li><a href="bio.html">BIO</a></li>
            <li><a href="contact.html">CONTACT</a></li>
            <li><a href="index.html" class="current">HOME</a></li>
          </ul>
          </nav>
    </div>

    <section id="content">

    <div id="container">

      <div id="imagewrap">
        <img src="Images/Images/Image1.jpg" id="front" />

        <div id="previous" class="buttons"></div>

        <div id="next" class="buttons"></div>
      </div>

    </div> <!-- end of content -->

    </section> <!-- end of container -->


    <div id="footer">
    </div>

    <script type="text/javascript" src="jquery-3.1.0.min.js"></script>
    <script type="text/javascript" src="JavaScript.js"></script>

    </body>

</html>

.js .js

$( document ).ready(function() {

$( "#imagewrap" ).hide();

function showPicture() {
$( "#imagewrap" ).fadeIn('slow');
}

setTimeout(showPicture, 2000);

$( "nav a" ).on('click', function(e){
    e.preventDefault();
    var url = this.href;
    $( "nav a.current" ).removeClass("current");
    $(this).addClass("current");
    $( '#container' ).remove();
    $( '#content').load(url + ' #content').hide().fadeIn('slow');
    });


counter = 1;
$( '.buttons' ).on('click', function(e){
    if (counter < 1 || counter > 5) {return false;}
    var id = e.target.id;
    if (id == "next" && counter < 5){counter++;
    } else if (id == "previous" && counter > 1){counter--;}
    getImage();
});
getImage = function() {
    document.getElementById("front").src = "Images/Images/Image" + counter + ".jpg";
}


});

contact.html contact.html

<!DOCTYPE html>
<html lang="en-US">

  <head>

    <meta charset="UTF-8">
    <title>Photography</title>
    <link rel="stylesheet" type="text/css" href="styles.css">

  </head>

  <body>

    <section id="content">

    <div id="container">

      <div id="contact" class="sections">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quia odit culpa excepturi itaque hic laborum odio nam deserunt ipsum dolor rerum repudiandae, quidem voluptatem nisi numquam tempora vel consequuntur harum! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ullam ut error consectetur eum delectus porro dolore repellendus quidem! Ad, dignissimos minus debitis nam sunt aliquid eius quam cum, omnis magni. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Saepe vero ducimus reprehenderit quibusdam esse sed, porro pariatur illum natus tempore? Iste laborum odio deleniti molestias praesentium delectus repudiandae consequatur corporis. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est fugit provident, labore expedita nostrum laborum nesciunt! Assumenda inventore repudiandae dignissimos animi autem, dolorem sint, incidunt officia quam porro, perspiciatis fuga.</p>
      </div>

    </div> <!-- end of content -->

    </section> <!-- end of container -->

  </body>

</html>

I am not posting the html for the other content as it is as with the contact.html or the css file to keep things short. 我没有发布其他内容的html,因为与contact.html或css文件一样,以保持简短。 Will do if requested. 如果需要,将做。 Thank you for your time. 感谢您的时间。

It's probably a problem with Delegated concept. 委托概念可能存在问题。

When you are navigating back to the Home, the content of your webpage is dynamically set and because of that, you lose event listeners. 当您导航回主页时,网页的内容是动态设置的,因此,您将丢失事件侦听器。

To avoid this, as mentionned by NeuTronas, you have to declare your event listeners using delegation . 为了避免这种情况,正如NeuTronas所提到的,您必须使用委托声明事件监听器。

Event listener without delegation 没有委托的事件监听器

$( '.buttons' ).on('click', function(e){
  // Will work only for element, with .buttons class, that have been created when accessing the webpage
})

Event listener with delegation 委托的事件监听器

$( document ).on('click', '.buttons', function(e){
  // Will work for all element with .buttons class, including those dynamically created
})

Check out this topic if you are still confused: Event binding on dynamically created elements? 如果您仍然感到困惑,请查看此主题: 动态创建元素上的事件绑定?

Use 采用

$(document).on('click','.buttons',function(e){

instead of: 代替:

$( '.buttons' ).on('click', function(e){

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

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