I have a problem with alert messages. It is displayed normally, and I can close it when the user presses x (close), but when the user tries to display it again (for example, click on the button event) then it is not shown. (Moreover, if I print this alert message to console, it is equal to [].) My code is here:

 <div class="alert" style="display: none">
   <a class="close" data-dismiss="alert">×</a>
   <strong>Warning!</strong> Best check yo self, you're not looking too good.
 </div>

和活动:

 $(".alert").show();

P.S!我只需要在某些事件发生后(例如,单击按钮)显示alert 消息.或者我做错了什么?

推荐答案

数据清除会完全删除该元素.取而代之的是使用jQuery的.ide()方法.

The fix-it-quick method:

Using inline javascript to hide the element onclick like this:

<div class="alert" style="display: none"> 
    <a class="close" onclick="$('.alert').hide()">×</a>  
    <strong>Warning!</strong> Best check yo self, you're not looking too good.  
</div>

<a href="#" onclick="$('alert').show()">show</a>

http://jsfiddle.net/cQNFL/

This should however only be used if you are lazy (which is no good thing if you want an maintainable app).

The do-it-right method:

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()
    })
})

然后将数据替换为隐藏在标记中的数据.Example at jsfiddle

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

这将使用data hide中指定的类隐藏所有元素,即:data-hide="alert"将使用alert类隐藏所有元素.

Xeon06提供了另一种解决方案:

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

这将只隐藏最近的父元素.如果你不想给每个alert 一个唯一的类,这是非常有用的.但是,请注意,您需要将关闭按钮放在alert 中.

距离jquery doc最近的定义:

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

Jquery相关问答推荐

逐个交换图像

如何向父元素添加类?

jquery 淡入淡出元素不显示样式为可见性:隐藏的元素

jQuery 与 javascript?

为什么我们在 jQuery 中使用({ })?

如何访问 JSON 对象名称/值?

在 contenteditable div 中的插入符号处插入 html

如何在jQuery中 Select 具有特定ID的所有元素?

即使通过Javascript代码判断,如何触发复选框单击事件?

使用 jQuery Select 最后 5 个元素

jQuery ajax 在 asp.net mvc 中上传文件

Jquery 和 HTML FormData 返回未捕获的 TypeError:非法调用

jQuery.extend 和 jQuery.fn.extend 的区别?

如何检测 window.print() 完成

通过单击按钮获取表格行的内容

Jquery live() 与委托()

上传文件前验证文件扩展名

如何判断值是否为 JSON 对象?

jquery在cookie中保存json数据对象

如何使用 jQuery 处理复选框的更改?