How to get a click event for each li, not all

2019-08-18 16:19发布

im trying to get this button to show a hidden div onClickwithin each li that will show over the post div in an absolute positioning. The problem is, on click, it's showing all of the hidden div's for all li's. Im using wordpress + buddypress, so each li's id has a unique ID

<li id="activity-<?php bp_activity_id(); ?>" class="activity" >

  <div id="post"></div>

  <div class="action">
   //my pop in stuff
  </div>

  <div id="post-actions-bar">   
    <button id="show">show</button>
  </div>

</li>

and here's my jquery that I thought would work. NOTE: I'm using .on() because there will be li's added dynamically.

$(document).on(  'click' , '.activity button#show' , function() {
   $('.action').show();
}); 

In a sense it does work, but it shows all of the .action div's for every li on the screen, I only want to show the one for that li's button that was clicked. I tried using .each() but It's not working. I'm ding something wrong (obviously lol)

Any ideas?

5条回答
趁早两清
2楼-- · 2019-08-18 16:39

You need to use $(this).closest('.activity').find('.action') instead of $('.action').

The reason for this is pretty simple - when you use $('.action') you simply retrieve all elements matching the selector .action which is completely unrelated to the event.

查看更多
一夜七次
3楼-- · 2019-08-18 16:50

Within the event handler $(this) refers to the one button that was clicked. So what you need to do is start from $(this) and traverse the DOM tree to get to the one .action that you want to show.

This is one way to do it, which I find preferable:

$(document).on('click' , '.activity button' , function() {
   $(this).closest(".activity").find(".action").show();
});

As an aside, your HTML implies that you are using the same id value for multiple elements. That's illegal and should be fixed -- it's only a matter of time before it causes trouble. Most of the time it's fine to assign a shared class to your elements instead of the same id and work with that.

查看更多
\"骚年 ilove
4楼-- · 2019-08-18 16:55

Here is a fiddle for you:

// html
<li>
    <div>Loading 1...</div>
</li>
<li>    
    <div>Loading 2...</div>
</li>​

// css
div
{
    display:none;
}​

// js
$("li").click(function(){

   // hide any showing ones
   $("li > div").hide(); 

   $(this).find("> div").show();

});
查看更多
霸刀☆藐视天下
5楼-- · 2019-08-18 16:58

I'd use the ul instead of the document to catch the click event

$('ul#parentofyouractivitylis').on('click', '.activity button', function(){
    $(this).closest(".activity").find(".action").show();
});
查看更多
倾城 Initia
6楼-- · 2019-08-18 17:01

You can't do them with a single bind since .action can't be reached from .activity or button#show using the same method. You can do something like this:

$(document).on('click', '.activity', function() {
    $(this).find(".action").show();
});

$(document).on('click', '#show', function() {
    $(this).closest(".action").show();
});​
查看更多
登录 后发表回答