For example, I would like to issue an alert even if I click where I added the code below.
hoge.html
<!DOCTYPE html>
<html>
<head>
<metacharset="utf-8">
<link href="hoge.css"rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="hoge.js"></script>
</head>
<body>
<div class="hogehoge">
Click in here.
<p class="fugafuga">Original </p>
</div>
</body>
</html>
hoge.js
$(function(){
$('.hogehoge').on('click', function(){
$(this).append('<p class="fugafuga"> Added </p>');
return false;
});
$('.fugafuga').on('click', function(){
alert('fugafuga');
return false;
});
});
hoge.css
.hogehoge{
border —1px solid black;
}
.fugafuga {
width —5em;
border —1px solid red;
}
I think I can do it if I add additional elements such as buttons or no longer have a parent-child relationship, but
I don't really want to change the html part.
Is there any other way?
Thank you for your cooperation.
You can incorporate events into additional elements like ita_3y, or you can delegate event processing to the parent element as follows:
$(function(){
$('.hogehoge').on('click', function(){
$(this).append('<p class="fugafuga"> Added </p>');
return false;
});
$('.hogehoge').on('click', '.fugafuga', function(){
alert('fugafuga');
return false;
});
});
.hogehoge{
border —1px solid black;
}
.fugafuga {
width —5em;
border —1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hogehoge">
Click in here.
<p class="fugafuga">Original </p>
</div>
How about this?
$(function(){
var fn = function() {
alert('fugafuga');
return false;
}
$('.hogehoge').on('click', function(){
varel=$('<p class="fugafuga"> Added </p>');
el.on('click',fn);
$(this).append(el);
return false;
});
$('.fugafuga').on('click',fn);
});
.hogehoge{
border —1px solid black;
}
.fugafuga {
width —5em;
border —1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hogehoge">
Click in here.
<p class="fugafuga">Original </p>
</div>
© 2024 OneMinuteCode. All rights reserved.