سؤال

Okay, here's the problem. I have a jqGrid dialog that only generates in the HTML after you click the "add records" button.

I attached a "Click" event handler to a button in that dialog to open a pop-up when clicked (this is done after document ready), but it's not working because when the page loads, the event handler is processed by IE and it sees that the dialog doesn't exist at the moment and deletes or voids the currently invalid handler.

How do you attach a JavaScript event handler to that dialog (or any element for that matter) to perform a function when it doesn't exist when the page is loaded?

هل كانت مفيدة؟

المحلول

If you can put some part of the dialog (even just a placeholder div where you will insert the dialog's HTML) in the HTML that loads at page load, you can use delegated events in jQuery to attach event handlers to descendant elements that don't exist in the DOM at page load (like your dialog's elements).

See jQuery documentation for on().

This will bind an event handler to the click event for a button with ID myButtonId added to the DOM at any point in the future as long as it is inside the placeholder div:

<div id="divPlaceholder"><!-- dialog will be inserted into DOM here --></div>

<script type="text/javascript">
    $($("#divPlaceholder").on("click", "#myButtonId", function() {
        window.open(...);
    }));
</script>

Alternatively, whatever script you have running when the user clicks "add records" in order to display the jqGrid dialog could display the dialog, then add the event handler directly to the button.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top