简体   繁体   English

访问动态生成的元素

[英]Accessing dynamically generated elements

When adding a dynamically added element, how can I get attributes for that element (when clicking on it, for example)? 添加动态添加的元素时,如何获取该元素的属性(例如,单击该元素时)? I figured out that I need to delegate an event, but I still can't access any of the attributes of that event. 我发现我需要委派一个事件,但仍然无法访问该事件的任何属性。

This JSFiddle shows the issue problem: https://jsfiddle.net/wgc499n9/ 此JSFiddle显示了问题所在: https ://jsfiddle.net/wgc499n9/

$(this).data('index') comes up as 'undefined' - I think $(this) is referencing 'document' instead of .remove_link ; $(this).data('index')出现为'undefined'-我认为$(this)引用的是'document'而不是.remove_link ; even the event data doesn't seem to have any useful information in it. 即使event数据似乎也没有任何有用的信息。 $(this).attr('id') also comes up as 'undefined'. $(this).attr('id')也显示为'undefined'。

In the end, I just need to be able to click that remove link to remove the row it's on. 最后,我只需要单击该remove链接即可删除其所在的行。 How can I accomplish that? 我该怎么做? I even tried inline JS, but that caused even stranger behavior. 我什至尝试了内联JS,但这甚至导致了陌生的行为。

PS I also learned that my dynamically added data-index attribute is not stored in the DOM; PS我还了解到,我动态添加的data-index属性没有存储在DOM中。 jQuery stores it separately, so its containing element has to be accessed by using .find() ...but I can't figure out how to use .find() to access the specific individual elements I need. jQuery单独存储它,因此必须使用.find()来访问其包含元素...但是我不知道如何使用.find()来访问我需要的特定单个元素。

Use element event(e) parameter instead this: 使用元素event(e)参数代替:

 let i = 0; $('#add').on('click', () => { $('#container').append(`<div>row #${(i+1)} <a "href="#" data-index="${i}" class="remove_link">remove</a></div>`); i++; }) $(document).on('click', '.remove_link', (e) => { //alert(JSON.stringify(e)); alert($(e.target).data('index')); }) 
 .remove_link { color: red; font-size: 0.8em; cursor: pointer; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <button id="add">Add row</button> <div id="container"></div> 

For more detail read difference b/w $(this) ans event.target. 有关更多详细信息,请阅读差异b / w $(this)和event.target。

In your event handler, this represent window. 在事件处理程序中, this代表窗口。 You have access to e.target to get the clicked element. 您可以访问e.target来获取被单击的元素。

This should works: 这应该工作:

$('#container').on('click', '.remove_link', (e) => {
    alert($(e.target).data('index'));
})

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

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