如何获得每个李而不是全部李的点击事件 [英] How to get a click event for each li, not all

查看:108
本文介绍了如何获得每个李而不是全部李的点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

im试图获取此按钮以在每个li内显示一个隐藏的div onClick,这些li将以绝对位置显示在post div上方.问题是,单击时会显示所有li的所有隐藏div.我使用的是wordpress + buddypress,因此每个li的ID都有一个唯一的ID

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>

这是我认为可行的我的jquery. 注意:我正在使用.on(),因为将动态添加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();
}); 

从某种意义上说它确实有效,但是它在屏幕上显示了每个li的所有.action div's,我只想显示被单击的li的按钮的所有.action div's.我尝试使用.each(),但无法正常工作.我在打错东西(显然是哈哈)

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)

有什么想法吗?

推荐答案

在事件处理程序$(this)中,是指单击的一个按钮.因此,您需要做的是从$(this)开始,然后遍历DOM树转到要显示的一个.action.

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();
});

顺便说一句,您的HTML表示您对多个元素使用相同的id值.这是非法的,应该予以解决-造成麻烦只是时间问题.在大多数情况下,可以为元素分配一个共享的class而不是相同的id并进行处理.

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.

这篇关于如何获得每个李而不是全部李的点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆