Reputation: 2866
In the following jquery code how can I include onclick event on <p>Click D3</p>
, I included d1 and d2's onclick p. I dont know how to include <p>Click D3</p>
click event in the same statement i.e. $(".d1,.d2").on('click','p',function(){
$(".d1,.d2").on('click','p',function(){
console.log($(this).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="d1">
<p>Click D1</p>
</div>
<div class="d2">
<p>Click D2</p>
</div>
<p>Click D3</p>
Upvotes: 0
Views: 41
Reputation: 746
add new class name for resolve it.
$('.d p').on('click', function(e){
console.log($(this).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="d d1">
<p>Click D1</p>
</div>
<div class="d d2">
<p>Click D2</p>
</div>
<div class="d">
<p>Click D3</p>
</div>
Upvotes: 0
Reputation: 497
If you do parent.on('click', element, function (){})
then you can't really do anything but add a div (.d3
) and select the p
inside that.. if you don't have any other p
tags, then you could change the event listener to :
$("body").on('click', 'p' ,function (){ console.log($(this).text()); });
OR You could wrap all of these p
tags inside one div too
$(".d1, .d2, .d3").on('click','p',function (){
console.log($(this).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="d1">
<p>Click D1</p>
</div>
<div class="d2">
<p>Click D2</p>
</div>
<div class="d3">
<p>Click D3</p>
</div>
Upvotes: 1