I have some list item tags in my jsp. Each list item has some elements inside, including a link ("a" tag) called delete. All that I want is to delete the entire list item when I click the link.

Here is the structure of my code:

$("a").click(function(event) {
  event.preventDefault();
  $(this).parent('.li').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li id="191" class="li">
  <div class="text">Some text</div>
  <h4><a href="URL">Text</a></h4>
  <div class="details">
    <img src="URL_image.jpg">
    <span class="author">Some info</span>
    <div class="info"> Text
      <div class="msg-modification" display="inline" align="right">
        <a name="delete" id="191" href="#">Delete</a>
      </div>
    </div>
  </div>
</li>

但这不管用.我是jQuery的新手,所以我try 了一些东西,比如:

$(this).remove();

This works, it deletes the link when clicked.

$("#221").remove();

This works, it deletes the indicated list item, but it's not "dynamic".

有人能给我点小费吗?

推荐答案

Simply use the .closest() method: $(this).closest('.li').remove();
It starts with the current element and then climbs up the chain looking for a matching element and stops as soon as it found one.

.parent()只访问元素的direct父元素,即div.msg-modification不匹配.li.所以它永远不会到达你想要的元素.

除了.closest()之外的另一个解决方案(判断当前元素,然后沿着链向上爬)是使用.parents()——但是,这需要注意的是,它不会在找到匹配的元素时立即停止(并且它不会判断当前元素,而是判断only个父元素).在你的情况下,这并不重要,但对于你正在try 做的事情来说,.closest()是最合适的方法.


Another important thing:

NEVER use the same ID for more than one element. It's not allowed and causes very hard-to-debug problems. Remove the id="191" from the link and, if you need to access the ID in the click handler, use $(this).closest('.li').attr('id'). Actually it would be even cleaner if you used data-id="123" and then .data('id') instead of .attr('id') to access it (so your element ID does not need to resemble whatever ID the (database?) row has)

Jquery相关问答推荐

在 Laravel 中使用 jQuery post 按相关值过滤 Select 选项,如何显示从控制器返回的数据?

如何在外部JS文件中使用带有参数的laravel路由

jQuery / Ajax - $.ajax() 将参数传递给回调 - 使用好的模式?

如何使用jQuery删除父元素

扩展 jQuery 插件的最佳方式

清除并刷新 jQuery Chosen 下拉列表

Google Maps API v3 infowindow 关闭事件/回调?

jQuery/JavaScript 碰撞检测

jQuery增量读取AJAX流?

如何在 jQuery 中存储全局值(不一定是全局变量)?

将返回的 JSON 对象属性转换为(较低的第一个)camelCase

数字键盘的keyCode值?

判断元素是否为 div

使用带有 HTML 表格的 jQuery UI 可排序

jQuery 插件:添加回调功能

如何隐藏 Twitter Bootstrap 下拉菜单

在jQuery中获取CSS规则的百分比值

jQuery: Select 不为空的数据属性?

jQuery attr 与props ?

如何获得两个日期对象之间的小时差?