简体   繁体   English

jQuery最近的()remove() <a>不能正常工作吗?</a>

[英]jQuery closest() remove() on <a> doesn't work?

Please see this page which has this code: 请查看包含以下代码的页面

<div class="pure-control-group query-brand-by-column">
    <!-- somethings else -->
    <div class="pure-u-1 pure-u-sm-1-24 control-group-sub">
        <a href="javascript:$(this).closest('.query-brand-by-column').remove();" class="pure-button danger">X</a>
    </div>
</div>

Clicking the X link should remove its ancestor div.query-brand-by-column as a whole but somehow it's not working. 单击X链接应将其祖先div.query-brand-by-column整体删除,但是不起作用。 I've checked jQuery docs and this answer and the code seems absolutely all right to me but it simply doesn't work. 我已经检查了jQuery文档和此答案 ,并且代码对我来说似乎绝对正确,但是根本行不通。 Any idea? 任何想法?

this in href doesn't refers to anchor element, thus it doesn't work. href中的this并不指向锚元素,因此不起作用。 It refers to window . 它是指window

You should bind element event handler using jQuery. 您应该使用jQuery绑定元素事件处理程序。

Script 脚本

$(document).on('click', '.pure-button danger' function(e) {
    e.preventDefault();
    $(this).closest('.query-brand-by-column').remove();
});

HTML 的HTML

<div class="pure-control-group query-brand-by-column">
    <!-- somethings else -->
    <div class="pure-u-1 pure-u-sm-1-24 control-group-sub">
        <a href="#" class="pure-button danger">X</a>
    </div>
</div>

I will not recommended, However you can use inline onclick handler. 我不会推荐,但是您可以使用内联onclick处理程序。

<a onclick="$(this).closest('.query-brand-by-column').remove();" href='#' class="pure-button danger">X</a>

Detach your javascript from your html and remove your item with a click event, right now you aren't triggering any click events: 从html分离您的javascript并使用click事件删除您的项目,现在您不会触发任何click事件:

<script>
$(function(){
 $('.pure-form').on('click','.query-brand-by-column a',function(){//this will create and delegate your click event to work on dynamically created items 
  $(this).closest('.query-brand-by-column').remove();
 });
});
</script>

这是你的答案,享受

  <a href="javascript:void(0);" onclick="return $(this).closest('.query-brand-by-column').remove();" class="pure-button danger">X</a>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM