使用jQuery单击隐藏父div

Kee*_*yne 7 html javascript jquery show-hide

所以我正在尝试编写一个超级简单的脚本,允许用户在.closediv内部抛出任何链接或按钮,当.close单击该链接时,它会自动关闭父容器.

以下是我目前正在尝试使用的内容:JSFiddle

我目前正在尝试使用的代码是:

HTML

<div class="well notice bg-green">
    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
    <p>This is a notice that is green.</p>
</div>
Run Code Online (Sandbox Code Playgroud)

CSS

.well {
    background: #f9f9f9;
    border-color: #f1f1f1;
    border-style: solid;
    border-width: 1px;
    padding: 15px 20px;
}
.notice {
    margin: 15px 0;
    padding: 0px 15px;
}
.well.bg-green {
    background: #dff0d8;
    border-color: #d6e9c6;
    color: #468847;
}
.close {
    color: #000;
    filter: alpha(opacity=20);
    float: right;
    font-size: 21px;
    font-weight: bold;
    line-height: 1;
    margin-top: 15px;
    opacity: .2;
    text-shadow: 0 1px 0 #fff;
}
.close:hover, .close:focus {
    color: #000;
    cursor: pointer;
    filter: alpha(opacity=50);
    opacity: .5;
    text-decoration: none;
}
button.close {
    background: transparent;
    border: 0;
    cursor: pointer;
    padding: 0;
    -webkit-appearance: none;
    -moz-appearance: none;
}
Run Code Online (Sandbox Code Playgroud)

JavaScript(jQuery)

$('.close').live("click", function () {
    $(this).parents('div').fadeOut;
});
Run Code Online (Sandbox Code Playgroud)

如果我的问题没有意义或者是否需要进一步阐述,请告诉我.谢谢!

Jas*_*n P 20

两个问题:

  • live() 在您的小提琴中的jQuery版本中不存在(在1.7中弃用,在1.9中删除)
  • fadeOut 是一个函数(你缺少执行它的parens)

http://jsfiddle.net/KF7S6/

$('.close').on("click", function () {
    $(this).parents('div').fadeOut();
});
Run Code Online (Sandbox Code Playgroud)

如果您希望它适用于动态元素,请使用此版本:

$(document).on('click', '.close', function () {
    $(this).parents('div').fadeOut();
});
Run Code Online (Sandbox Code Playgroud)