数据清除会完全删除该元素.取而代之的是使用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.