2012-08-07 36 views
0

選擇DIV我有這樣的結構:從id和class的jQuery

<div id="list_articles"> 
    <div id="article"> 
    <label>Select:</label><input type="checkbox" class="checked_art" id="1001" /> 
    <div id="hide" style="display:none;" class="1001"> 
     //Code here... 
    /div> 
    </div> 
    <div id="article"> 
    <label>Select:</label><input type="checkbox" class="checked_art" id="1002" /> 
    <div id="hide" style="display:none;" class="1002"> 
     //Code here... 
    /div> 
    </div> 
</div> 

我想要做的是,當我檢查我的複選框,得到了「隱藏」根據複選框的ID,例如: 如果我檢查這一個:

<input type="checkbox" class="checked_art" id="1001" /> 

我想刪除的

<div id="hide" style="display:none;" class="1001"> 

心中已經風格Ë在試圖這樣使用jQuery:

$(".checked_art").live('click',function() 
{ 
    var id = $(this).attr('id'); 
    var checked = $(this).attr('checked'); 
    var a = "#hide ."+id; 
    if(checked == 'checked') 
    { 
    $(a).show(); 
    } 
    else 
    { 
    $(a).hide(); 
    } 
} 

但它只是第一個元素的作品,我想它做的是與所有的人,任何幫助嗎?謝謝。

+0

你不應該具有相同ID的多個元素...使用類具有類似功能/行爲組多個元素。 ID應該用來唯一標識元素。 – scunliffe 2012-08-07 16:19:28

回答

1
$(".checked_art").click(function(){ 
    $(this).next().toggle(); 
}); 

順便說一下,ID必須是唯一的。

jsFiddle example

+1

lol @代碼行數的差異 – Th0rndike 2012-08-07 16:20:25

+1

謝謝,它的工作原理。 – Enrique 2012-08-07 16:25:09

+0

@EnriqueAlonsoGonzalezMeza - 如果您覺得這個答案有幫助,請考慮選擇它作爲接受的答案和/或upvoting它。 – j08691 2012-08-07 17:17:48

0

首先,改變這一行使用類,而不是ID:

<div style="display:none;" class="1001 hide"> 

然後,改變你的函數使用類.hide,而不是ID #hide和刪除之間的空間.hide.1001選擇器(指示同一級別)

$(".checked_art").on('click',function() 
{ 
    var id = $(this).attr('id'); 
    var checked = $(this).attr('checked'); 
    var a = ".hide."+id; 
    if(checked == 'checked') 
    { 
    $(a).show(); 
    } 
    else 
    { 
    $(a).hide(); 
    } 
} 

然而,一個更簡單的代碼是(根據你的HTML):

$(".checked_art").on('click',function() 
{ 
    if ($(this).is(':checked')) { 
     $(this).next('div.hide').hide(); 
    } else { 
     $(this).next('div.hide').show(); 
    } 
} 

甚至更​​簡單:

所有的
$(".checked_art").on('click',function() 
{ 
    $(this).next('div.hide').toggle(); 
} 
0

首先,.live()已被棄用。如果您使用的是最新的jQuery的版本,你應該使用.on()

$(document).on("click", ".checked_art", function() { 
    // ... 
}); 

此外,ID必須是唯一的。因此,您應該將「隱藏」標識符更改爲class屬性,而不是id屬性。

此外,您idclass屬性應該以一個字母,而不是數字開頭。您可以通過在以數字開頭的每個屬性前添加一個常用字符串(如「e」)來解決此問題。例如,您可以將「1001」更改爲「e1001」。

無論如何,你的問題是idclass之間的空間。這:

var a = "#hide ."+id; 

應該是這樣的:

var a = ".hide."+id;