Javascript jQuery选择动态创建的html元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10280569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:39:49  来源:igfitidea点击:

jQuery select dynamically created html element

javascriptjqueryjquery-selectorsdynamically-generated

提问by Almas Adilbek

There are a lot of asked questions with almost similar titles with this question of mine, but you know I didn't find an answer.

My simple question is: I have button, when I click on it, javascript creates modal window

有很多与我的这个问题标题几乎相似的问题,但你知道我没有找到答案。

我的简单问题是:我有按钮,当我点击它时,javascript 会创建模态窗口

<div class="aui-dialog">
     html here... 
     <button id="closeButton">Close</button>
</div>

just after <body>tag.

I can bind click event of close button with no problem using jQuery live:

就在<body>标签之后。

我可以毫无问题地使用 jQuery live绑定关闭按钮的点击事件:

$("#closeButton").live("click", function() { 
    alert("asdf"); // it calls
    $("body").find(".aui-dialog").remove();
});

My problem is, I cannot select that dynamically created modal window div by its classname. So that I could call jQuery .remove() method to make close action. Now I know, I must deal with dynamic elements in another way.

What way?

我的问题是,我无法通过其类名选择动态创建的模态窗口 div。这样我就可以调用 jQuery .remove() 方法来进行关闭操作。现在我知道了,我必须以另一种方式处理动态元素。

有什么办法?

EDIT:
I think it's important to mention this:
I dont' create the modal window myself, I use liferayportal. It has built-in javascript framework AUI(YUI) that creates that modal window. I can just create that close button inside it in its view.

编辑:
我认为提及这一点很重要:
我自己不创建模态窗口,我使用liferay门户。它具有创建该模式窗口的内置 javascript 框架AUI( YUI)。我可以在它的视图中创建关闭按钮。

EDIT 2:
Modal window div class attribute value is: "aui-component aui-panel aui-dialog aui-widget-positioned"

编辑 2:
模态窗口 div 类属性值为:“ aui-component aui-panel aui-dialog aui-widget-positioned

采纳答案by binarious

Create a reference when you're creating the modal window:

创建模态窗口时创建一个引用:

var modalWindow = $('<div class="aui-dialog">html here... <button id="closeButton">Close</button></div>');
// later...
modalWindow.remove();

To your edit:

给你的编辑:

Get the window via jQuery's parentwhen the button is inside the modal window:

parent当按钮位于模态窗口内时,通过 jQuery 获取窗口:

$('#closeButton').on('click',function() {
    $(this).parent().remove();
    return false;
});

回答by JUlinder

Since jquery will read the current DOM-state when page loads:

由于 jquery 会在页面加载时读取当前的 DOM 状态:

jQuery( document ).ready(function( $ ) {

it will miss the elements you generate post to page load.

它会错过您在页面加载后生成的元素。

One simple solution is to listen for clicks on document, and filter with the class or element-type that you want to use to execute your code. That way jquery will find new elements generated under document, after page load.

一种简单的解决方案是监听对文档的点击,并使用要用于执行代码的类或元素类型进行过滤。这样 jquery 会在页面加载后找到文档下生成的新元素。

$(document).on("click", '#closeButton', function(){
$(".aui-dialog").remove();
});

回答by ahmadalibaloch

Many users will come on this page when they want to select some element generated runtime by JQuery and it failed, like me.
The solution is simply approach the root (the parent) of your randomly generated element and then get inner by jQuery TAG selection. For example you generate many TDs of users in a table at runtime, the element having your users list is a table with id tblUsers then you can iterate over runtime generated TRs or TDs as following:

很多用户会在想要选择由 JQuery 生成的运行时的某个元素时会来到这个页面,但它失败了,就像我一样。
解决方案是简单地接近随机生成元素的根(父元素),然后通过jQuery TAG selection获取内部元素。例如,您在运行时在一个表中生成许多用户 TD,包含您的用户列表的元素是一个 id 为 tblUsers 的表,然后您可以迭代运行时生成的 TR 或 TD,如下所示:

$("#tblUsers tr").each(function(i){
    alert('td' + i);
});   

further if you have inputs in tds you can go deep in selection as

此外,如果您在 tds 中有输入,则可以深入选择

$("tblUsers tr td input")

Another case could be a randomly generated dialog or popup, then you have to approach its root(parent) and next same selection by TAG as stated above.

另一种情况可能是随机生成的对话框或弹出窗口,然后您必须按照上述方式通过 TAG 处理其根(父)和下一个相同的选择。

回答by Joseph

You could do a few things, but first, if you are using jQuery 1.7, better use .on(). it has replaced .live()which is deprecated.

您可以做一些事情,但首先,如果您使用的是 jQuery 1.7,最好使用.on(). 它已取代.live()已弃用的。

if you have no control over the building of the modal but know that the button is a direct child of the modal, then use parent()

如果您无法控制模态的构建,但知道该按钮是模态的直接子级,则使用 parent()

$('#closeButton').on('click',function() {
    $(this).parent().remove();
    return false;
});

if the button is somewhere deep in the parent but has a fixed depth from the parent, use parents()which gets all ancestors of the element, and then filter it to a specific depth. if the close was 2 levels deep, the index of :eq()would be 1.

如果按钮位于父级深处,但与父级有固定深度,则使用parents()which 获取元素的所有祖先,然后将其过滤到特定深度。如果收盘深度为 2 个级别,则 的指数:eq()将为 1。

$('#closeButton').on('click',function() {
    //where N is zero-indexed integer, meaning first item of the set starts with 0
    $(this).parents(':eq(N)').remove(); 
    return false;
});

another way is to add the handler when the modal is created

另一种方法是在创建模态时添加处理程序

var modal = $('modalHTML');

$('#closeButton',modal).on('click',function(){
    //modal still refers to the whole modal html in this scope
    modal.remove();
});

//show modal

回答by Almas Adilbek

I found an answer, hope it would be helpful for developers who faced with dynamicallygenerated html with IFRAMEinside.

If you have a button (#closeButton) inside that IFRAME, and you want select iframe parent window's dom elements, just add second argument window.parent.documentfor your selector:

我找到了一个答案,希望它对面对内部带有IFRAME 的动态生成的 html 的开发人员有所帮助。 如果您在该 IFRAME 中有一个按钮 (#closeButton),并且您想要选择 iframe 父窗口的 dom 元素,只需为您的选择器添加第二个参数:

window.parent.document

// This functions is inside generated IFRAME
$("#closeButton").on("click", function() {        
       // body - is your main page body tag
       /* Will alert all html with your dynamically 
          generated html with iframe and etc. */
       alert($('body', window.parent.document).html()); 
       return false;
}); 

回答by Stian

UPDATED:

更新:

You can use:

您可以使用:

$(".aui-dialog").live('click', function() {
    $(this).remove();
    return false;
});)

This attach an event handler for all elements which match the current selector, now and in the future. Please not that this method is depreciated in newer version of jQueryand you should consider using .on()instead of .live().

这为现在和将来与当前选择器匹配的所有元素附加了一个事件处理程序。请不,此方法在新版本贬值的jQuery,你应该考虑使用.on()替代.live()