jQuery - 如何使用无线电输入显示/隐藏元素?

时间:2012-07-22 07:43:32

标签: jquery

我遵循html结构:

 <div id="options">
    <input type="radio" id="option0" value="option0" checked='checked' /><label>All</label>
    <input type="radio" id="option1" value="option1" /><label>Option 1</label>
    <input type="radio" id="option2" value="option2" /><label>Option 2</label>
    <input type="radio" id="option3" value="option3" /><label>Option 3</label>
 </div>

 <p id="sentence1">This is an example of sentence 1</p>
 <p id="sentence2">This is an example of sentence 2</p>
 <p id="sentence3">This is an example of sentence 3</p>

我想在选中“全部”选项时显示所有句子,并在“选项1”选中时显示#sentence1 ..依此类推。

任何帮助将不胜感激。

谢谢! Rifki

1 个答案:

答案 0 :(得分:0)

试试这个:

<div id="options">
    <input type="radio" id="option0" value="option0" name="options" checked='checked' /><label>All</label>
    <input type="radio" id="option1" value="option1" name="options" /><label>Option 1</label>
    <input type="radio" id="option2" value="option2" name="options" /><label>Option 2</label>
    <input type="radio" id="option3" value="option3" name="options" /><label>Option 3</label>
 </div>

 <p id="sentence1">This is an example of sentence 1</p>
 <p id="sentence2">This is an example of sentence 2</p>
 <p id="sentence3">This is an example of sentence 3</p>

Jquery:

$(function(){
var allSentences = $("p[id^=sentence]");
$("INPUT[type=radio]").click(function(){

    var _this = $(this);
    if(_this.val()=="option0"){
           allSentences.show();
    }else{
        allSentences .hide();
        $("#"+_this.val().replace("option", "sentence")).show();
    }

});
});

检查此jsfiddle http://jsfiddle.net/7u3uS/3/