ajax将html注入div但保留html元素包括它们的id

I am using some ajax to call a php file that returns some html (an image and couple of buttons) and then place the contents of this into a div. The trouble is that I want to be able to use the id of one of the buttons that is returned from the php to hook up an event handler. The output of the source if I do view source in browser simply shows the div that the html is injected into and not the html:

<div class="displaysomething"></div>

My AJAX is as follows:

$(document).ready(function () { 
   getServiceDisplay();
   $('#stop-service').click(function(e)
   {
       e.preventDefault();
       runHDIMService();
   });

}

function getServiceDisplay(){
$.ajax(
{ 
    url: 'includes/dosomething.php',
    type: 'POST',
    success: function(strOutput) 
    {
        $(".displaysomething").html(strOutput);
        }               
    }); 
};

PHP - Ultimately returns a button amongst other stuff. This is what I need to hook up to the event handler, based on its id.

echo '<input id="stop-service" type="button" value="Run" class="'.$strRunActionButtonClass.'"/>';

If I simply put a button on the page without injecting it using AJAX into the div my button hookup code works great.

Does anybody have any ideas?

Thanks

In jQuery, the .click(... method of adding an event handler will only add the event to existing elements. New elements added later are no included.

You can use the jQuery on method of event binding to include elements added later.

$("body").on("click", "#stop-service", function(e){
    e.preventDefault();
    runHDIMService();
});

I have created a simple example on JSFiddle.

The problem is that

$(document).ready(function () { 
   getServiceDisplay();
   $('#stop-service').click(function(e) // this doesn't exists yet
   {
       e.preventDefault();
       runHDIMService();
   });

This should work:

function getServiceDisplay(){

$.ajax(
{ 
    url: 'includes/dosomething.php',
    type: 'POST',
    success: function(strOutput) 
    {
        $(".displaysomething").html(strOutput);
        // so after you attached the div from ajax call just register your event
        $('#stop-service').click(function(e)
        {
            e.preventDefault();
            runHDIMService();
        });               
    }); 
};