0

I have a javascript object

function A()
{
    this.ini = function()
    {
        $('#test').html('<button id="click" >Hi</button>');
    }    

    $('#click').on('click',function(){
        alert('Hi');
    });
}

http://jsfiddle.net/G2MUE/1/

But I have a problem, the event onClick is not used.

Thanks for your help

Ajouve
  • 9,095
  • 24
  • 83
  • 128

4 Answers4

6

Try this

$(document.body).on('click', "#click" ,function(){
    alert('Hi');
});

You are attaching handler before the element is in the DOM.

Manoj Nama
  • 639
  • 3
  • 9
3
function A()
{
    this.ini = function()
    {
        $('#test').html('<button id="click" >Hi</button>');
    }    

    $(document).on('click', '#click', function(){
        alert('Hi');
    });
}

http://jsfiddle.net/G2MUE/7/

Martin
  • 401
  • 2
  • 8
0

You dont need to put it in initializeation.Try like

function A()
{    
    $('#test').html('<button id="click" >Hi</button>');             
    $('#click').on('click',function(){
       alert('Hi');
    });
}
A();

See this DEMO

Gautam3164
  • 28,027
  • 10
  • 58
  • 83
-1

You're trying to bind a handler to an element that doesn't exist. Try something like this:

http://jsfiddle.net/pdT24/

function A() {
    this.ini = function () {
        $('<button id="click" >Hi</button>')
            .click(clickfn)
            .appendTo('#test');

    }

    var clickfn = function (e) {
        alert('Hi');
    };
}
var a = new A();
a.ini();

An alternative would be event delegation with on():

$('#test').on('click', '#click', function() { ... });
Jason P
  • 26,853
  • 3
  • 31
  • 45