【发布时间】:2010-11-29 16:30:38
【问题描述】:
我有一个带有单选按钮列表和“选定搜索”区域(<span>)的 DIV。单击“选定搜索”区域时,会出现一个下拉层,其中包含带有单选按钮列表的 DIV。选择单选按钮后,“选定搜索”区域会使用该单选按钮的文本进行更新,并且下拉层折叠/消失。
这是我的 HTML 结构:
<div class="radio-btns"><span class="selected-search">A</span>
<div class="radio-btns-wrapper">
<label><input type="radio" value="a" id="a" checked>A</label>
<label><input type="radio" value="b" id="b">B</label>
<label><input type="radio" value="c" id="c">C</label>
<label><input type="radio" value="d" id="d">D</label>
</div>
</div>
知道如何用 jQuery 来实现吗?任何帮助将不胜感激。
谢谢。
** 编辑 **
自从我在 2010 年提出这个问题以来,我现在对 jQuery 进行了一些改进,所以这里有一个修改后的标记,因为上面的标记并不理想。
新的 HTML 结构:
<a href="#" class="selected-search">A</a>
<div class="radio-btns-wrapper">
<label><input type="radio" value="a" id="a" name="radio" checked>A</label>
<label><input type="radio" value="b" id="b" name="radio">B</label>
<label><input type="radio" value="c" id="c" name="radio">C</label>
<label><input type="radio" value="d" id="d" name="radio">D</label>
</div>
jQuery 脚本:
这是对@Greg 以下回答的改进:
//If JS is available, hide the radio buttons container
$(".radio-btns-wrapper").hide();
//DIV with radio buttons will slide down when clicking on .selected-search
//The default action on the link <a> is removed (preventDefault();) to avoid having the page jump to the back top
$(".selected-search").click(function (e) {
$(".radio-btns-wrapper").slideDown();
e.preventDefault();
});
//Click on radio button and have target text update with radio button's text
$("input[type=radio]").click(function () {
// Alter the text of the span to the text of the clicked label
$(".selected-search").text($(this).parent().text());
// Now hide the radios
$(".radio-btns-wrapper").slideUp();
});
由于所选答案中的演示链接不再起作用,因此我创建了自己的演示。你可以在这里看到它:http://jsfiddle.net/rzea/vyvLvgkh/4/
【问题讨论】:
-
请参阅"Should questions include “tags” in their titles?",其中的共识是“不,他们不应该”!
-
好的,怎么样?我读了帖子,当然没有达成共识。此外,对于我所读到的“标签”,只要它们有意义并有助于标题更清晰,就可以成为问题标题的一部分。
标签: jquery