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

4
  • The #click element does not yet exist when you try to bind your handler to it. Commented Nov 21, 2013 at 14:52
  • Ok I find, stackoverflow.com/questions/10920355/… Commented Nov 21, 2013 at 14:53
  • What are your thought behind this function? Seems kind of pointless to instantiate something with hard coded values. Commented Nov 21, 2013 at 14:54
  • Take a look at; stackoverflow.com/questions/15090942/… Commented Nov 21, 2013 at 14:57

4 Answers 4

6

Try this

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

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

Sign up to request clarification or add additional context in comments.

Comments

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/

Comments

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

1 Comment

why need to down it..??Any reason
-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() { ... });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.