简体   繁体   English

将事件附加到动态元素

[英]attach event to dynamic element

Hey im having a problem attaching an event to an element im dynamically generating. 嘿我有一个问题将事件附加到动态生成的元素。 I would appreciate any advice on solving the issue im not sure whether its the method that im using to attach the event or whether its something else: 我将不胜感激任何有关解决问题的建议我不确定它是用于附加事件的方法还是其他的东西:

for (var i = 0; i < array.length; i++) { 
itemlist=itemlist.concat('<pre'+' id="pres'+i+'"'+'>'+array[i]+'</pre>');

var name = '#pres'+i;
$( name ).click(function() {
  alert( "Handler for .click() called." );
});
}

I also tried this method which i found on stack overflow however yielded no result : 我也试过这个方法,我发现堆栈溢出但是没有产生结果:

var name = '#pres'+i;
$(name).on('click', function() {
    alert( "Handler for .click() called." );
});

Whilst inspecting in chrome all of the elements exist with the correct ID, however the jquery event i have attached does not perform its alert. 虽然在chrome中检查所有元素都存在正确的ID,但是我附加的jquery事件不会执行其警报。 I have looked at some solutions however i do not want to attach the same function to all "" tags however attaching the same event to each of the ones in the loop would be acceptable. 我已经查看了一些解决方案,但是我不想将相同的函数附加到所有“”标记,但是将相同的事件附加到循环中的每个标记都是可以接受的。 Any help would be appreciated :) 任何帮助,将不胜感激 :)

Instead of generating unique id attributes, which makes the code needlessly more complex and can be a pain to maintain, you could instead use a single common class and attach a single delegated event handler to all the elements. 您可以改为使用单个公共类并将单个委托事件处理程序附加到所有元素,而不是生成唯一的id属性,这会使代码不必要地变得更加复杂并且可能很难维护。 Try this: 尝试这个:

$('#myContainer').on('click', '.foo', function() {
    // handle the element click here...
    console.log($(this).text());
});

var html = '';
for (var i = 0; i < array.length; i++) { 
    html += '<pre class="foo">' + array[i] + '</pre>';
}
$('#myContainer').append(html);

Rory McCrossan's answer is the simplest way to do it if you just add the elements at the beginning and set their .click after that. Rory McCrossan的答案是最简单的方法,如果你只是在开头添加元素并在之后设置他们的.click。
However, if you call the generating function sometime later than that, I'd suggest using something like this, a function that sets the .click event handler for each element when it is created. 但是,如果你在晚些时候调用生成函数,我建议使用类似这样的函数,这个函数在创建每个元素时设置.click事件处理程序。

You can still have your IDs and so on, you just don't really need them. 你仍然可以拥有自己的身份证等等,你根本就不需要它们。

  var itemlist=[] var array=["Element 1","Element 2","Element 3"] for (var i = 0; i < array.length; i++) { element=$('<pre' + ' id="pres' + i + '"' + '>' + array[i] + '</pre>'); $(element).click(function () { alert("Handler for .click() called."); }); itemlist.push(element); } $("body").append(itemlist) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

You need to use the on method in the container that contains all pre elements, like code bellow. 您需要在容器中使用包含所有pre元素的on方法,如下面的代码。

Suppose you have this result: 假设你有这个结果:

<div class="container-pre">
  <pre id="pres1" data-id="1" class="pre-element">Some text 1</pre>
  <pre id="pres2" data-id="2" class="pre-element">Some text 2</pre>
  <pre id="pres3" data-id="3" class="pre-element">Some text 3</pre>
</div>

Then your jQuery configuration would like this: 然后你的jQuery配置会这样:

$(document).ready(function() {
  $(".container-pre").on("click", ".pre-element", function(e) {
        var elem = $(e.currentTarget);
        var id = elem.attr("data-id");
        alert( "Handler for .click() called at element " + id);
    });
});

You can see this plunker with this code in action: 您可以使用此代码查看此plunker:

https://embed.plnkr.co/v61GxazfsT8RscuMTxI9/ https://embed.plnkr.co/v61GxazfsT8RscuMTxI9/

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

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