jQuery - Event of button added to div tag not fired
I am using SmartCart.js
script to add the products from one div tag to another, but when I running this code the event to Add Product button is not fired. Why?
var HTML = '<div class="scProductListItem">'+
'<table border="0" cellpadding="2" cellspacing="2">'+
'<tr>'+
'<td rowspan="3"><img width="100px" src="http://webscopia.com/wp-content/upl开发者_如何学JAVAoads/2011/06/Google.plus-get-an-invite-from-me.jpg" alt="Not availabel" /></td>'+
'<td><strong><span id="prod_name'+'test'+'">'+'detail_product[0]'+'</span></strong></td>'+
'</tr>'+
'<tr>'+
'<td>'+
'<input type="button" rel="'+'test'+'" class="scItemButton scBtn" value="Add Product">'+
'</td>'+
'</tr>'+
'</table>'+
'<input type="button" value="TestButton" name="Test" onclick="Alert()"/>'+
'</div>';
$('#sc_productlist').append($(HTML));
Add Product. These button's event I am not able to receive.
Alert() is not a valid function
alert(''); is a valid function
That's because you don't have any event specified for that button. Try to add an onclick
event:
'<input type="button" rel="'+'test'+'" class="scItemButton scBtn" value="Add Product" onclick="alert(\'Add product\');">'+
If you have added an event using jQuery, then it doesn't work because you only add the event to the element that exist at that time. You would have to add the event to the new button after creating it, or use the delegate method to add an event handler to a parent element that already exists:
$('#sc_productlist').delegate('.scItemButton', 'click', function(){
// code to handle the event
});
You need to bind the onclick
event after appending the HTML to your div or you can use the jQuery live function to bind the event.
精彩评论