When there is an onclick to the jQuery parent element, I want to adapt it to the child element after adding it in append, etc.

Asked 2 years ago, Updated 2 years ago, 47 views

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.

jquery

2022-09-29 21:33

2 Answers

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>


2022-09-29 21:33

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>


2022-09-29 21:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.