Case: you have a <select>
, when it is changed, creating new elements (example: <a>
), and you want to handle click
event of new <a>
<select id="chooser">
<option value="1">Restaurants</option>
<option value="2">Hotels</option>
</select>
<div id="result">
</div>
Solution 1: listen .click()
event after new <a>
elements are created
$('#chooser').change(function(e){
var val = $(this).val();
var result = getResult(val); // return array
$.each(result, function(key, value) {
$('#result').append($('<a href="#" class="shop-name">'+ value.name +'</a>'));
});
$('.shop-name').click(function(e) {
// do something
});
});
Solution 2: using .delegate()
even no a.shop-name
elements
$(document).delegate('.shop-name', 'click', function(event) {
// do something
});
$('#chooser').change(function(e){
var val = $(this).val();
var result = getResult(val); // return array
$.each(result, function(key, value) {
$('#result').append($('<a href="#" class="shop-name">'+ value.name +'</a>'));
});
});