单击事件不能动态附加div

时间:2013-05-27 08:25:07

标签: javascript jquery google-maps google-places-api

我正在使用Google Place Autocomplete

当我在自动填充文本框中搜索任何内容时,Google会在我的html中添加一些div,

<div class="pac-container" style="position: absolute; z-index: 1000; width: 134px; left: 885px; top: 412px; display: none;">
    <div class="pac-item remove">This is me </div>
  <div class="pac-item"><b>A</b>ustralia</div>
  <div class="pac-item"><b>A</b>bbas Town, Karachi, Sind, Pakistan</div>
  <div class="pac-item"><b>A</b>ustria</div>
  <div class="pac-item"><b>A</b>rgentina</div><div class="pac-item"><b>A</b>rizona</div></div>

现在您可以注意到第一个孩子离子pac-container与其他孩子不同,我为了某种目的动态地添加了div。现在,如果我想将事件绑定到该div,那么我就无法工作了。

这就是我正在做的事情

$('.remove').live('click', function () {
   console.log("working");
});

提前致谢。 的更新

我认为你们误解了我,如果我将我的动态div放到除pac-container之外的任何其他地方,那么它可以工作但是当我把我的div放在pac-container中然后它不起作用而我尝试了几乎每个人的解决方案,但没有人工作 希望你们现在明白这个场景。感谢

更新2

这是我上传工作的link

5 个答案:

答案 0 :(得分:1)

您没有提到您正在使用的jquery版本,但jquery 1.7 live已弃用on,因此您可以替换live绑定这个:

 $('.pack-container').on('click', '.remove', function(){
     console.log("working");
  });

如果pack-container也是动态创建的元素,那么您需要修改以上内容:

 $(document).on('click', '.remove', function(){
     console.log("working");
  });

此处的官方文档http://api.jquery.com/on/

答案 1 :(得分:0)

$(document).on('click', '.remove', function () {
   console.log("working");
});

答案 2 :(得分:0)

$(document).on('click','.remove', function () {
   //Your code
});

您应该使用.on委派活动。顺便说一下.live已经过时了。而是使用.on方法。问题是页面加载时无法动态添加元素以将事件绑定到它们。因此发生错误。尝试将事件绑定到专利,在您的情况下可能是另一个div或document会没事。

了解更多

Direct vs. Delegated - jQuery .on()

答案 3 :(得分:0)

我已经尝试过你的代码正常工作。我认为你正在dom ready函数中执行这个click功能。如果你尝试点击dom ready中的动态元素功能意味着它不会工作..

在jsfiddle中检查你的代码        http://jsfiddle.net/mNq5X/

   <div class="pac-container">
   <div class="pac-item remove">This is me </div>
   <div class="pac-item"><b>A</b>ustralia</div>
   <div class="pac-item"><b>A</b>bbas Town, Karachi, Sind, Pakistan</div>
   <div class="pac-item"><b>A</b>ustria</div>
   <div class="pac-item"><b>A</b>rgentina</div><div class="pac-item"><b>A</b>rizona</div>     
  </div>

JS

$('.remove').live('click', function () {
  console.log("working");
});

所以你的解决方案是在追加下面的div

后添加上面的点击功能
          <div class="pac-item remove">This is me </div>

答案 4 :(得分:0)

由于您的div是动态附加的,我认为您的点击事件代码应该在附加div之后放置。否则$('。remove')将返回'null',您的点击事件将无效。

相关问题