jQuery:在 <li> 中选择 <p> 标签

标签 jquery this parent-child

我正在尝试使用 jquery 淡出 <p> <li> 内的标签当选择删除按钮时。

<ul>
    <li>
        <p>Here is some text!</p>
        <span class="delete">Delete</span>
    <li>
<ul>

这是到目前为止我的 jQuery:

$(".delete").click(function(){
    //Needs to select the <p> tag within the same <li> 
    $("p").fadeOut(); 
});

最佳答案

按照引用的结构,简单地说:

$(".delete").click(function(){
    //Needs to select the <p> tag within the same <li> 
    $(this).prev("p").fadeOut(); 
});

如果p可能不是删除链接的直接前导,那么您可以执行以下操作:

$(".delete").click(function(){
    //Needs to select the <p> tag within the same <li> 
    $(this).closest("li").find("p").fadeOut(); 
});

...这将淡出它在 li 中找到的所有 p 元素,或者这样:

$(".delete").click(function(){
    //Needs to select the <p> tag within the same <li> 
    $(this).closest("li").find("p").first().fadeOut(); 
});

...这将淡出它在 li 中找到的第一个 p 元素,或者这样:

$(".delete").click(function(){
    //Needs to select the <p> tag within the same <li> 
    $(this).prevAll("p").first().fadeOut(); 
});

...它将淡出它发现的从删除链接向后工作的第一个同级。

引用文献:

  • prev - 查找直接的上一个同级,或者如果它与选择器不匹配则什么也不找到
  • closest - 找到与选择器匹配的最近的祖先
  • find - 查找与选择器匹配的所有后代
  • prevAll - 以相反的文档顺序查找与选择器匹配的所有先前同级元素(例如,从当前元素向后工作)
  • first - 只抓取当前集合中的第一个元素

关于jQuery:在 <li> 中选择 <p> 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6914655/

相关文章:

jquery - 将背景颜色从一个单元格复制到另一个表格单元格

java - 使用 outerClass.this 从内部类内部访问外部类

PHP这个伪变量

Android:其父 View 之外的 subview 不响应点击事件

javascript - @Input() 未按预期在 Angular 2 应用程序中的父子组件之间传递

css - 在 SASS 中,是否可以将子元素规则的值与父元素规则相匹配?

php - 使用 AJAX 和 PHP 从 MYSQL 检索 ID 号,然后使用检索到的 ID 进行 hashchange URL

javascript 无法对元素应用查找

javascript - jquery animate() 函数有问题

javascript - 在带有原型(prototype)的 Javascript 中使用此关键字?