2014-02-26 174 views
4

所以我想寫一個超級簡單的腳本,將允許用戶拋出任何鏈接或按鈕類.close在一個div內,當這個.close鏈接被點擊時,它自動關閉父容器。使用jQuery隱藏父母div點擊

以下是我目前正在與合作: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> 

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; 
} 

的JavaScript(jQuery的)

$('.close').live("click", function() { 
    $(this).parents('div').fadeOut; 
}); 

讓我知道,如果我的問題沒有意義,或者如果需要更多的闡述。謝謝!

+3

'fadeOut'應該是'淡出()' –

+0

在jQuery 1.7中,.live()方法已過時。使用.on()附加事件處理程序。 – j08691

回答

16

兩個問題:

  • live()不會在你的小提琴(在1.7過時,在1.9移除)
  • fadeOut是一個功能版本的jQuery的存在(你失蹤括號來執行它)

http://jsfiddle.net/KF7S6/

$('.close').on("click", function() { 
    $(this).parents('div').fadeOut(); 
}); 

如果你想讓它在動態元素的工作,使用這個版本:

$(document).on('click', '.close', function() { 
    $(this).parents('div').fadeOut(); 
}); 
+1

是的,這表明我真的缺乏JavaScript經驗,但非常感謝您的幫助。你的代碼工作完美。我非常感謝。 –

3

工作演示http://jsfiddle.net/gL9rw/

問題是.live現在已經過時了。

如果你渴望:What's wrong with the jQuery live method?:)

代碼

$('.close').on("click", function() { 
    $(this).parents('div').fadeOut(); 
}); 
+1

感謝您分享該鏈接!我不知道'.live'已被棄用,我試圖將我的代碼從其他Stack Overflow問題中拼湊出來(正如我相信每個人都注意到的)。哈哈。 –

2

http://jsfiddle.net/6Xyn4/4/

$('.close').click(function() { 
    $(this).parent().fadeOut(); 
}); 

推薦到位的現在使用.click()棄用.live()

1

試試這個,應該是沒有​​fadeOut

$('.close').click(function() { 
    $(this).parents('div').fadeOut(); 
}); 
0

.live()已經死了。使用.on()委託。你也錯過了一些東西,檢查以下

$('body').on("click", '.close', function() { 
     $(this).parents().fadeOut(); 
    }); 

Fiddle