我會建議開始具有良好的HTML基礎。我可能會在每個div
中使用一個隱藏的單選按鈕,並在單擊div
時檢查或取消選中它。單選按鈕將是提交選定值的表單上的有效項目。
HTML:
<div class="choice">
<input id="choice_1" type="radio" name="choice" value="choice_1" />
<label for="choice_1">Chicago</label>
</div>
<div class="choice">
<input id="choice_2" type="radio" name="choice" value="choice_2" />
<label for="choice_2">Los Angeles</label>
</div>
<div class="choice">
<input id="choice_3" type="radio" name="choice" value="choice_3" />
<label for="choice_3">San Francisco</label>
</div>
的JavaScript:
$(document).ready(function() {
var choices = $('.choice');
choices.on('click', function(event) {
var choice = $(event.target);
choice
.find('[name="choice"]')
.prop('checked', true)
.trigger('change');
});
var inputs = $('.choice input');
inputs.on('change', function(event) {
var input = $(event.target);
var choice = $(this).closest('.choice');
$('.choice.active').removeClass('active');
choice.addClass('active');
});
});
演示:jsfiddle
另一種方法:如果你想多一次
與單選按鈕僅在一個
所以選擇單選按鈕組一次處於活動狀態。如果這不是您想要的行爲,您可以使用隱藏的複選框並將其打開和關閉。
HTML:
<div class="choice">
<input id="choice_1" type="checkbox" name="choice_1" value="choice_1" />
<label for="choice_1">Chicago</label>
</div>
<div class="choice">
<input id="choice_2" type="checkbox" name="choice_2" value="choice_2" />
<label for="choice_2">Los Angeles</label>
</div>
<div class="choice">
<input id="choice_3" type="checkbox" name="choice_3" value="choice_3" />
<label for="choice_3">San Francisco</label>
</div>
的JavaScript:
$(document).ready(function() {
var choices = $('.choice');
choices.on('click', function(event) {
var choice = $(event.target);
var input = choice.find('[type="checkbox"]');
input
.prop('checked', !input.is(':checked'))
.trigger('change');
});
var inputs = $('.choice input');
inputs.on('change', function(event) {
var input = $(event.target);
var choice = $(this).closest('.choice');
if (input.is(':checked')) {
choice.addClass('active');
}
else {
choice.removeClass('active');
}
});
});
演示:jsfiddle
將這項工作? http://api.jquery.com/toggle/ – Scott
像引導可摺疊的東西? http://twitter.github.com/bootstrap/javascript.html#collapse你當然需要自定義代碼來發送表單提交div的狀態。 –
@Scott:好吧,切換似乎顯示/隱藏,而不是突出顯示/「un-highlighting」,所以不是我真正需要的,儘管有一些共同之處。 – MiniQuark