事件不适用于附加的html标记

事件不适用于附加的html标记

本文介绍了jquery click()事件不适用于附加的html标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的问题有意义之前,我需要解释一些事情。在我的第一页上,我有一个主div,我使用jquery load()方法从另一个页面加载标记。我正在加载的html链接到我的脚本所在的.js页面。 js页面是我操纵主div的内容的地方。
在我的js页面上,我遍历一个从数据库中提取的变量数组,并将它们追加到主div。在for循环中,我将每行包装在自己的div中,并包含一个锚标记。锚标签是我想要附加click()方法的,所以我可以在单击它时调用它。我已经尝试了父>子选择器等,但是对于锚标记没有任何作用。我的代码:

There are a couple of things I need to explain before my question makes sense. On my first page I have a main div where I'm loading markup from another page using the jquery load() method. The html I'm loading is linked to a .js page where my script is. The js page is where I'm manipulating the content of the main div.On my js page I loop through an array of variables I pull from a database and append() them to the main div. In the for loop I wrap each row in its own div and include an anchor tag. The anchor tag is what I want to attach the click() method to so I can call a function once it is clicked. I've tried the parent > child selector among others, but nothing works for the anchor tag. My code:

//this is the query to my parse database

query.find({
  success: function(results) {
    for (i = 0; i < results.length; i++){

        activity = results[i].get("activity");
        scene = results[i].get("location");
        neighborhood = results[i].get("neighborhood");
        date = results[i].get("date");
        details = results[i].get("details");
        time = results[i].get("time");
        search.push([activity, scene, neighborhood, date, details, time]);

        for (i = 0; i < search.length; i++) {

            //append each row of results to mainDiv inside of their own div with an anchor tag at the end of each row.
            //when the anchor tag is clicked I want to call a function, but none of the selectors I've tried have worked.

            $('#mainDiv').append("<div id='event'>" + search[i].join(' ') + "<a href='#' id='interested'>Interested?</a></div>");
        }

    };// closes for loop
    },//closes success function
  error: function(error) {
    alert("Error: " + error.code + " " + error.message);
  }
}); //closes find


推荐答案

我在这里找到了答案:

I found an answer here:Newly appended div doesn't inherit event handler in document ready

快捷方式事件处理程序(例如click(),mouseover()等)仅适用于DOM上可用的元素页面加载。当动态附加元素时,您必须将事件附加到静态父元素,并提供您希望委托事件的过滤器,如下所示:

The shortcut event handlers (such as click(), mouseover() etc) will only apply to elements which are available to the DOM on page load. When appending elements dynamically you have to attach the event to a static parent element, and supply a filter which you wish to delegate events to, like this:

这是我的解决方案:

$("#mainDiv").on('click', '.interested', function(){
       alert("working");
   });

这篇关于jquery click()事件不适用于附加的html标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 06:06