简体   繁体   English

jQuery在动态生成的div上不起作用

[英]jQuery not working on dynamically generated divs

I am creating a portfolio section of a website which utilizes Flickr's REST api. 我正在使用Flickr的REST api创建网站的投资组合部分。 The list of portfolio items, however, is generated dynamically by this code: 但是,投资组合项目列表是通过以下代码动态生成的:

$.ajax({
  url: "https://api.flickr.com/services/rest?method=flickr.photoSets.getList&user_id=********@N04&format=json&nojsoncallback=1&api_key=***********",
  context: document.body
}).done(function(results) {
  results.photosets.photoset.map(function(item) {
    var imgUrl = "https://farm" + item.farm + ".staticflickr.com/" + item.server + "/" + item.primary + "_" + item.secret + "" + ".jpg";
    $(" #portfolio_horizontal_container ").append(
      '<div class="portfolio_item interior design"> \
          <img  src=' + imgUrl + '    alt="" /> \
          <div class="port-desc-holder"> \
              <div class="port-desc"> \
                  <div class="grid-item"> \
                      <h3><a href="folio-single">Quisque non augue</a></h3> \
                      <span>Photography /   Web design</span> \
                  </div> \
              </div> \
          </div> \
      </div>'
    )
  })
});

I also have another plugin which manages the portfolio interactions and style. 我还有另一个插件可以管理项目组合的交互和样式。 However when the DOM elements for the portfolio items get loaded this other plugins just doesn't work, thus the functionality it applies to the portfolio is non existent. 但是,当加载项目组合项的DOM元素时,此其他插件将不起作用,因此,不存在适用于项目组合的功能。 I have tried and tried to solve this with no success. 我已经尝试并试图解决此问题,但没有成功。 Any thoughs? 可以吗

The code that attaches event handlers to your DOM elements will need to be re-run whenever new elements are added to the page. 每当将新元素添加到页面时,都将需要重新运行将事件处理程序附加到DOM元素的代码。

In the same function as above, you'll need to re-invoke the plugin so that it will be aware of the new structure. 在与上述相同的功能中,您需要重新调用该插件,以便它知道新的结构。

If I understood your problem, you could create a function which create the event and call it in the ajax done: 如果我理解您的问题,则可以创建一个函数来创建事件并在完成的ajax中调用它:

    function bindEvent(id){
         //initialize the plugin for the given id
    }

then you can call bindEvent, after the append inside the ajax.done using the id of the newly inserted html. 那么您可以使用新插入的html的id在ajax.done内的追加之后调用bindEvent。

or 要么

If it's an event that you want to bind you can use 如果是您要绑定的事件,则可以使用

$('body').on('click', 'my-dinamic-id', function(){...})

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

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