Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use two 'onclick' event

Tags:

javascript

Below is my code, why isn't it working when I click on Appended text ?

1: click on This is a paragraph.

2: click on Appended text

3: Must show Appended item with color red.

$(document).ready(function(){
    $(".ali").click(function(){
        $(this).parent().append("<b class='reza'>Appended text</b>");
    });
    $(".reza").click(function(){
        $(this).append("<li style='color:red'>Appended item</li>");
    });
});
<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>

    <p><span class="ali"> This is a paragraph. </span> </p>


</body>
</html>
like image 347
Alireza Avatar asked Dec 07 '25 08:12

Alireza


1 Answers

Since the element with class "reza" is not created yet, you need to define click event on future element with "reze" class. Check the below working code.

$(document).ready(function(){
    $(".ali").click(function(){
        $(this).parent().append("<b class='reza'>Appended text</b>");
    });
    $("body").on("click",".reza",function(){
        $(this).append("<li style='color:red'>Appended item</li>");
    });
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>

<p><span class="ali"> This is a paragraph. </span> </p>


</body>
</html>
like image 173
Radhesh Vayeda Avatar answered Dec 09 '25 22:12

Radhesh Vayeda