我希望在C#对象不为null时运行fadeIn。我想这些细节应该不重要,但以防万一它的asp.net MVC 3 - razor。
的jQuery
<小时/>
<script type="text/javascript">
function MessageFadeIn(){
$('messageLbl').fadeIn('slow', function () {
//Animation complete
});
}
</script>
ASP.NET
<小时/>
@if (ViewBag.Message != null)
{
//run jquery to fade this label in below...the label shouldnt display unless jQuery runs
<label id="messageLbl" style="background-color:Red;color:White;">@ViewBag.Message</label>
}
我该如何做到这一点?
答案 0 :(得分:3)
在您的HTML中将CSS display: none;
添加到style
属性。这将使label
默认不显示。
@if (ViewBag.Message != null)
{
//run jquery to fade this label in below...the label shouldnt display unless jQuery runs
<label id="messageLbl" style="display: none; background-color:Red; color:White;">@ViewBag.Message</label>
}
和jQuery(在#
之前添加messageLbl
表示它是ID Selector):
<script type="text/javascript">
$(document).ready(function {
$('#messageLbl').fadeIn('slow', function () {
//Animation complete
});
});
</script>
正确解释 @Raynos 后,如果文档中不存在#messageLbl
,则没有问题。
little jsFiddle来演示它是如何运作的。
答案 1 :(得分:3)
messageLbl仅在消息不为空时才存在,因此它将起作用。
如果你尝试在不存在的对象上淡入淡出,jQuery不会抛出错误。它只是优雅地失败。