2010-08-09 39 views
0

我想弄清楚如何使用jquery過濾輸入/輸出內容與複選框。對於jquery來說,我很新,我不知道如何以正確的方式來處理這個問題。如何使用複選框過濾內容? - jQuery

我想三個複選框是這樣的:

<div class="check_filter"> 
    <div id="filter"> 
     <input type="checkbox" id="apple" /><label for="apple">Apple</label> 
     <input type="checkbox" id="pear" /><label for="pear">Pear</label> 
     <input type="checkbox" id="peach" /><label for="peach">Peach</label> 
    </div> 
</div> 

然後,我將有可能被過濾的內容:

<div id="content" > 
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> 
    <p>Vestibulum consectetur ipsum sit amet urna euismod imperdiet aliquam urna laoreet.</p> 
    <p>Curabitur a ipsum ut elit porttitor egestas non vitae libero.</p> 
    <p>Pellentesque ac sem ac sem tincidunt euismod.</p> 
    <p>Duis hendrerit purus vitae nibh tincidunt bibendum.</p> 
    <p>Nullam in nisi sit amet velit placerat laoreet.</p> 
    <p>Vestibulum posuere ligula non dolor semper vel facilisis orci ultrices.</p> 
</div> 

我想篩選出的數據的最佳方式時,該複選框被選中或未選中。

謝謝你對此的任何幫助。

+1

哪些數據需要過濾?某些段落標籤? – 2010-08-09 18:36:24

回答

1
$('#apple').change(function(){ 
    var checked = $(this).is(":checked"); 
    if(checked) 
    { 
     filterContentForApple(); 
    } 
}); 

,然後像...

function filterContentForApple() 
{ 
    $('#content p').each(function(){ 
     if($(this).is(":contains('apple')")//or some other condition 
     { 
     $(this).hide(); 
     } 
     else{ 
     $(this).show(); 
     } 
    }) 
} 

當然,你總是可以讓一個過濾器()函數,它的功能謂詞作爲參數,但是這應該給你的總體思路如何去做你所要求的。

+0

我不確定在上面說「匹配某些謂詞...」的地方。我能做些什麼嗎? – DonDraper01 2010-08-09 19:15:48

+0

無論您需要做什麼類型的線路過濾,都要這樣做。 – 2010-08-09 19:33:17

1

你可以把課上要隱藏,然後使用toggleshowhide他們<p> S:

HTML:

<div id="content" > 
    <p class="apple">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> 
    <p>Vestibulum consectetur ipsum sit amet urna euismod imperdiet aliquam urna laoreet.</p> 
    <p class="pear">Curabitur a ipsum ut elit porttitor egestas non vitae libero.</p> 
    <p class="apple peach">Pellentesque ac sem ac sem tincidunt euismod.</p> 
    <p>Duis hendrerit purus vitae nibh tincidunt bibendum.</p> 
    <p>Nullam in nisi sit amet velit placerat laoreet.</p> 
    <p>Vestibulum posuere ligula non dolor semper vel facilisis orci ultrices.</p> 
</div> 

的jQuery:

$("#apple").toggle(
     function() { 
     $('.apple').hide(); 
     }, 
     function() { 
     $('.apple').show(); 
     } 
    );