Reputation: 10049
I have a javascript object
function A()
{
this.ini = function()
{
$('#test').html('<button id="click" >Hi</button>');
}
$('#click').on('click',function(){
alert('Hi');
});
}
But I have a problem, the event onClick is not used.
Thanks for your help
Upvotes: 0
Views: 159
Reputation: 28773
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
Upvotes: 0
Reputation: 471
function A()
{
this.ini = function()
{
$('#test').html('<button id="click" >Hi</button>');
}
$(document).on('click', '#click', function(){
alert('Hi');
});
}
Upvotes: 3
Reputation: 639
Try this
$(document.body).on('click', "#click" ,function(){
alert('Hi');
});
You are attaching handler before the element is in the DOM.
Upvotes: 6
Reputation: 27022
You're trying to bind a handler to an element that doesn't exist. Try something like this:
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() { ... });
Upvotes: -1