当单击关闭按钮时隐藏警报而不是删除它

12

在我的页面中,使用以下警告框显示来自服务器的响应:

    <div id="yes" class="alert alert-success" role="alert" style="display: none;">
      <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
      <strong>Pronto!</strong> cadastro efetuado com sucesso! 
    </div>

当我点击警告框中的关闭按钮时,是否有任何方法可以将其隐藏而非从页面中移除?我尝试了这个(根据这里的说明进行),但没有成功:

$('#my-alert').on('close.bs.alert', function () {
  $(this).hide();
})

更新

我也尝试了这个:

    $('button.close').on("click", function(){
        $(this).parent().hide();
    });
但是仍然存在同样的问题,当我点击关闭按钮时,警告提示被移除。

1
“hide” 不会移除元素,这是什么问题? - Ram
@undefined 我不想要删除,但是当我点击关闭按钮时就会发生这种情况。 - Kleber Mota
该元素是由Bootstrap而不是hide调用删除的。 - Ram
我按照这个答案的指示解决了这个问题:https://dev59.com/AmYr5IYBdhLWcg3wmLRk#13550556 - Kleber Mota
可能是推特Bootstrap警告消息关闭并再次打开的重复问题。 - Kleber Mota
我用这个提示解决了这个问题:https://dev59.com/AmYr5IYBdhLWcg3wmLRk#13550556 - Kleber Mota
6个回答

9
我找到的解决方案是:

解决这个问题的方法:

Create a new data attribute for hiding an element.

Javascript:

$(function(){
    $("[data-hide]").on("click", function(){
        $("." + $(this).attr("data-hide")).hide();
        // -or-, see below
        // $(this).closest("." + $(this).attr("data-hide")).hide();
    });
});

and then change data-dismiss to data-hide in the markup. Example at jsfiddle.

$("." + $(this).attr("data-hide")).hide();

This will hide all elements with the class specified in data-hide, i.e: data-hide="alert" will hide all elements with the alert class.

基于此主题发布的答案:Twitter Bootstrap提示框消息的关闭和再次打开


4
使用Bootstrap的close.bs.alert事件:
$('.alert').on('close.bs.alert', function (event) {
    event.preventDefault();
    $(this).addClass('hidden');
  });

3
我会使用 $(this).fadeOut() 来代替。 - Galley

1
我已尝试这些解决方案,但对我没有用。 您可以通过从标记中简单地删除"data-dismiss"属性并创建新函数来实现它:
    $('.alert').on('click','.close',function(){
        $(this).closest('.alert').slideUp();
   });

0

在上面的评论的帮助下完成,并删除了"data-dismiss"。

$('.close').on('click', function(e) {
     $('.alert').fadeOut();
});

0

那个上面的回答是正确的,但有一个问题。所以,请用这个答案。

使用[data-hide=alert]来检测点击事件比使用[data-hide]更好。因为如果您在同一屏幕中多次使用data-hide属性,则隐藏特定div时会遇到问题。因此,还需要使用[{yourAttributeName}={attributeValue}]值来检测点击事件。

$("[data-hide=alert]").on("click", function(){ 
     $("." + $(this).attr("data-hide")).hide();
     // -OR-
     // $(this).closest("." + $(this).attr("data-hide")).hide();
     
     // -OR-
     // ... do stuff as above answer 
     // otherwise do changes as per your need
}

-2

你做错了,试试这个。在你的情况下,按钮类是close,而div id是yes。

$('button.close').on('click', function () {
  $("#yes").hide();
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接