2014-03-31 94 views
-1

我卡在這裏..嘗試顯示與匹配檢查的輸入元素的ID的類名的div。查找ID和類之間的匹配

這是我走到這一步,什麼錯..

HTML:

<input type="radio" id="one" name="choice" checked /> 
<input type="radio" name="choice" id="two"/> 
<div class="one"> 
    Hello! 
</div> 
<div class="two"> 
    Goodbye! 
</div> 

的jQuery:

$('input').click(function(){ 

    var currentElement = $(this).parent().find('input:checked').id; 

    $(document).getElementsByClassName(currenElement).show(); 

}); 

CSS:

div{ 
    display: none; 
} 
+0

'getElementsByClassName'不是一個jQuery方法,你會最好使用onchange事件,'id'是一個DOM節點屬性。你正在混合所有它 –

+0

謝謝,現在知道出了什麼問題! –

+1

不知道爲什麼人們downvoting這篇文章..這是考慮到標籤更好的問題之一... – Lix

回答

1

有jQuery的對象沒有財產id。爲了得到一個元素的ID,你需要attr('id')

var currentElementId = $(this).parent().find('input:checked').attr('id'); 

但是,整個事情可以不混合JS和jQuery來完成:

$('.' + currentElementId).show(); 

因此,假設沒有錯誤在你的方法 - 我們獲取一個檢查過的輸入元素的ID,然後查找類名與我們剛剛獲取的ID相同的元素,然後顯示該類的所有元素。

這是你的工作示例:http://jsfiddle.net/N8yVt/1/

(請注意,我添加了一個隱藏功能,讓你無論是看你好再見或)

1

你正在混合jquery和javascript -

試試這個 -

$('input').click(function(){ 
    var id = $(this).parent().find('input:checked').attr('id'); 
    $('.' + id).show() 
}); 
1

嘗試

//use change event 
$('input').change(function() { 
    //hide all other inputs other than the target one 
    $('div').hide().filter('.' + this.id).show() 
}).filter(':checked').change(); //to initialize the initial display 

演示:Fiddle

+0

除了一件事情,工作很好,'這'是不是在這個更大的圖片。我用一個鏈接觸發它。我應該做一個變量而不是這個? –

+0

你可以編輯小提琴給你正確的標記 –

+0

正如在這個小提琴:http://jsfiddle.net/NN2Zn/ –