如何用其值替换select的标签? [英] How to replace the label of select with its value?
问题描述
HTML:
<input type="radio" name="timeformat" id="timeformat-a" value="am/pm" checked="checked" /> <b>am/pm</b>
<input type="radio" name="timeformat" id="timeformat-b" value="24 hours" /> <b>24 hours</b>
<select id="default-start-time" class="select check-list">
<option value="" label="--Select--">--Select--</option>
<option value="00:00" label="12:00 AM">12:00 AM</option>
<option value="00:30" label="12:30 AM">12:30 AM</option>
<option value="01:00" label="01:00 AM">01:00 AM</option>
<option value="01:30" label="01:30 AM">01:30 AM</option>
<option value="02:00" label="02:00 AM" selected>02:00 AM</option>
<option value="02:30" label="02:30 AM">02:30 AM</option>
</select>
当我选择24小时格式时,应该显示选项值.
When i choose the 24 hours format the option values should display.
jquery:
$("input[name='timeformat']").click(function() {
if($(this).val()=='24 hours')
{
// code which replaces label with the option value
}
});
jquery的外观如何?
How should the jquery look??
推荐答案
如果在<option>
元素中同时具有label
属性和文本内容,则<label>
将具有优先级.
If you have both a label
attribute and text content in an <option>
element the <label>
will take priority.
您可以将值复制到标签中,如下所示:
You can copy the values into the label like this:
$('#default-start-time option').attr('label', function() {
return this.value;
});
类似地,您可以将文本内容复制回标签中,如下所示:
similarly you can copy the text content back into the label like this:
$('#default-start-time option').attr('label', function() {
return this.innerHTML;
});
请参见 http://jsfiddle.net/alnitak/cLuZa/
请注意,(至少在Chrome中)两者都不会导致控件更改其当前显示的值.它们仅在您再次单击<select>
元素时出现.我还在努力...
Note that (in Chrome, at least) neither will cause the control to change its current displayed value. They only appear when you click on the <select>
element again. I'm still working on that...
编辑,这是我的最终答案:
EDIT here's my final answer:
$("input[name='timeformat']").click(function() {
var ampm = $(this).val() !== '24 hours'; // get mode
var sel = $('#default-start-time')[0]; // get the <select> element
$('option', sel).attr('label', function() {
return ampm ? this.innerHTML : this.value;
});
sel.selectedIndex += 0; // force refresh
});
这篇关于如何用其值替换select的标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!