I would like to proceed with $('.test2') in the following source.
I'm in trouble because I can't move.
Please let me know.
// I'll try rewriting it for now.
$('#hoge') .html('<li>test1</li>div class="test1">click here</div>');
// This works
$('.test1').click(function(){
console.log('test1 done');
alert('test1 done');
// Actually, I want to insert aax process here to retrieve the data and then put it in the next line.
$('#hoge').html('<li>test2</li>div class="test2">click here(this is problem.notwork)</div>');
});
// This doesn't work
$('.test2').click(function(){
console.log('test2done');
alert('test2 done.ok!!');
});
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<divid='hoge'></div>
Ajax is an asynchronous communication, so when $('.test2') .click...
, the target does not exist.
I think there are several ways, but I think the quick one is the delivery.
$('#hoge').on('click', '.test2', function(){
....
});
Alternatively, you may want to add an event listener after adding elements.
When you specify a click processing function in $('.test2').click(...)
, the element for .test2
has not yet been created.
The solution is to add $('.test2') .click(...)
and .test2
.
$('.test1').click(function(){
console.log('test1 done');
alert('test1 done');
$('#hoge').html('<li>test2</li>div class="test2">click here(this is problem.notwork)</div>');
// Move over here
$('.test2').click(function(){
console.log('test2done');
alert('test2 done.ok!!');
});
});
I don't think it feels good to add all the complex tags in .html()
, so I recommend that you create separate tags and .append
to the parent element.
$('.test1').click(function(){
console.log('test1 done');
alert('test1 done');
$('#hoge') .html(').append([
$('<li>test2</li>'),
$('<div class="test2">click here(this is problem.notwork)</div>')
.click(function(){// Add an event listener to these created elements
console.log('test2done');
alert('test2 done.ok!!');
})
]);
});
© 2024 OneMinuteCode. All rights reserved.