2014-03-19 45 views
-2
相同的div ID

我的問題很簡單解釋,但很難(對我來說)解決 一個環節都必須隱藏(或切換)幾個具有相同的ID顯示/隱藏使用jQuery

<div class="buttons"> 
<a id="showall">All</a> 
<a class="showSingle" target="1">Morning</a> 
<a class="showSingle" target="2">APM</a> 
<a class="showSingle" target="3">Night</a> 
</div> 

<div id="div1" class="targetDiv">Lorum Ipsum1</div> 
<div id="div2" class="targetDiv">Lorum Ipsum2a</div> 
<div id="div2" class="targetDiv">Lorum Ipsum2b</div> 
<div id="div3" class="targetDiv">Lorum Ipsum3</div> 

在這個例子中

<a class="showSingle" target="2">APM</a> 

應顯示

<div id="div2" class="targetDiv">Lorum Ipsum2a</div> 
<div id="div2" class="targetDiv">Lorum Ipsum2b</div> 

與此jQuery的

jQuery(function(){ 
     jQuery('#showall').click(function(){ 
       jQuery('.targetDiv').show(); 
     }); 
     jQuery('.showSingle').click(function(){ 
       jQuery('.targetDiv').hide(); 
       jQuery('#div'+$(this).attr('target')).show(); 
     }); 
}); 

JS Fiddle test

+7

'ID' **對於每個元素都必須是唯一**。改爲使用'classes'。 – Vucko

+0

你爲什麼要爲它們做jQuery()? – Shahar

+0

@Shahar:另一個庫也可能使用'$'。 – David

回答

0

你可以使用,而不是ID相對

http://jsfiddle.net/XwN2L/3564/

$(function(){ 
     $('#showall').click(function(){ 
       jQuery('.targetDiv').show(); 
     }); 
     $('.showSingle').click(function(){ 
       var self = $(this); 
       $('.targetDiv').hide(); 
       $('.targetDiv[rel=div' + self.attr('target') +']').show(); 
     }); 
}); 

HTML

<div rel="div1" class="targetDiv">Lorum Ipsum1</div> 
<div rel="div2" class="targetDiv">Lorum Ipsum2a</div> 
<div rel="div2" class="targetDiv">Lorum Ipsum2b</div> 
<div rel="div3" class="targetDiv">Lorum Ipsum3</div> 

,或者你甚至可以使用類,問題是你有多個ID wi同名。 ID必須是唯一的

0

首先,你應該使用類,而不是多個ID,如已在評論中提到的。還有一種方法可以做到這一點。試試這個來選擇所有具有相同ID的元素。

$('div[id="div2"]') 

它會給你如預期的2個div。這裏是JSBin Demo

PS:我發佈這個答案只是爲了幫助其他人的替代品。我不打算鼓勵在代碼中使用不好的做法。

0
<!DOCTYPE HTML> 
<html> 
<head> 
<title>Example</title> 
<style> 
div[class]{display:none;} 
</style> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
<script type="text/javascript"> 
$(document).ready(function(){ 
    $('.showSingle').click(function(){ 
     $('div[class]').hide() 
     var id=$(this).attr('target') 
     $('.div'+id).show() 
     }) 
    $('#showall').click(function(){ 
     $('div[class]').show() 
     }) 
}) 
</script> 
</head> 
<body> 

<div id="buttons"> 
<a id="showall">All</a><br/> 
<a class="showSingle" target="1">Morning</a><br/> 
<a class="showSingle" target="2">APM</a><br/> 
<a class="showSingle" target="3">Night</a><br/> 
</div> 

<div class="div1">Lorum Ipsum1</div> 
<div class="div2">Lorum Ipsum2a</div> 
<div class="div2">Lorum Ipsum2b</div> 
<div class="div3">Lorum Ipsum3</div> 
</body> 
</html>