介绍
在jQuery中操作选择框需要其他技能和交互作用,但并不复杂。 本文将帮助您完成有关选择框的操作,而不会遇到任何问题。
选择框创建
这应该是简单而直接的。
jQuery('#some_element').append('
');
2011年1月6日更新 –三种选择选择框选项的方式。
//select select box option
jQuery('#selectboxid option').attr('selected', true);
jQuery('#selectboxid option').attr('selected', selected);
$("#selectboxid").attr('selectedIndex', indexnumber);
使用jQuery选择Box选项
这是在选择框中添加选项的代码。 只需粘贴并编辑其中的某些部分即可满足您的需求。
//obj is the list of option values
function(obj)
{
var create = '
';
jQuery('#some_element').append(create);
}
另外,您可以在元素列表中创建选项,然后使用纯jQuery将其追加。
function(id, obj) { jQuery('#some_element').append('
'); jQuery.each(obj, function(val, text) { jQuery('#'+id).append( jQuery('
');
for(var i = 0; i '+obj[i]+' Getting Value in Select Box
We might need to know what the current value of the option selected is.
[js]
//#selectbox is the id of the select box
jQuery('#selectbox option:selected').val();
[code lang="js"]
You can get the text of the option by doing this.
//#selectbox是选择框的ID
jQuery('#selectbox option:selected')。text();
//#selectbox是选择框的ID
$(“#selectList option [value ='thisistheone']”)。text();
//#selectbox是选择框的ID
$(“#selectList选项:第一”).text()
//#selectbox是选择框的ID
$(“#selectList选项:eq(3)”)。text()
//#selectbox是选择框的ID
$(“#selectList option:not(option:first,option:last)”)。each(function(){
$(this).text();
});
[/ cc]
在选择框中获取多个值
使用此代码检索多个值。
jQuery('#some_element:selected').each(function(){
alert(jQuery(this).text());
alert(jQuery(this).val());
});
var current = [];
jQuery('#some_element:selected').each(function(index, selectedObj){
current[index] = $(selectedObj).text();
});
var foo = jQuery('#multiple :selected').map(function(){return jQuery(this).val();}).get();
在选择框中删除元素
这里没有什么特别的。 只需粘贴此代码并对其进行修改,那么将要删除的项目就是您选择的内容。
jQuery('#selectbox: selected').remove();
Here we will remove all elements except the first and last one.
//#selectbox is the id of the select box
$("#selectbox option:not(option:first, option:last)").remove();
在选择框中选择选项
这样做以在选择框中选择一个选项。
jQuery('#selectbox option').attr('selected', 'selected');
取消选择选项
逆转上面的代码
jQuery('#selectbox option').attr('selected', false);
onChange事件找到选定的选项
$('#selectbox').change(function(){
var val = $(this).find('option:selected').text();
alert('i selected: ' + val);
});
onchange find select box selected items.
$('#selectbox').change(function(){
$(this).find('option:selected').each(function () {
alert('i selected: ' + $(this).text());
}
});
结论
如果您正确地遵循了这些步骤,则应该把事情做好。 如您所见,这并不难!
</ s> </ s> </ s>
资源:
http://hungred.com/how-to/tutorial-jquery-select-box-manipulation-plugin/
From: https://www.sitepoint.com/jquery-select-box-manipulation/