Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

javascript - jQuery select dynamically created html element

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

<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:

$("#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?

EDIT:
I think it's important to mention this:
I dont' create the modal window myself, I use liferay portal. 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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...