我有两个选择 html 标签。每个选择选项 html 标签的值都有不同的数组。我想合并两个 `var selectBox 和两个 Jquery,因为功能相同,但“id”不同。
如何做到这一点?有可能吗?
HTML:
<select id="textlist">
<option value="" selected><option>
</select>
<select id="placelist">
<option value="" selected><option>
</select>
选择 html 标签 1:
jQuery(document).ready(function($){
jQuery('#textlist').change(function(){
jQuery('.texts').hide();
jQuery('#' + jQuery(this).val()).show();
});
});
var options = [
{ "text" : "Text 1", "value" : "Text1" },
{ "text" : "Text 2", "value" : "Text2" }
];
var selectBox = document.getElementById('textlist');
for(var i = 0, l = options.length; i < l; i++){
var option = options[i];
selectBox.options.add(new Option(option.text, option.value, option.selected));
}
jQuery("#placelist").html(jQuery("#placelist option").sort(function (a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}))
选择 html 标签 2:
jQuery(document).ready(function($){
jQuery('#placelist').change(function(){
jQuery('.places').hide();
jQuery('#' + jQuery(this).val()).show();
});
});
var options = [
{ "text" : "Place 1", "value" : "Place1" },
{ "text" : "Place 2", "value" : "Place2" }
];
var selectBox = document.getElementById('placelist');
for(var i = 0, l = options.length; i < l; i++){
var option = options[i];
selectBox.options.add(new Option(option.text, option.value, option.selected));
}
jQuery("#placelist").html(jQuery("#placelist option").sort(function (a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}))
最佳答案
尝试创建一个函数来重用代码,就像我在下面所做的那样:
fucntion addOptions(id, className, options){
jQuery(document).ready(function($){
jQuery('#'+id).change(function(){
jQuery('.'+className).hide();
jQuery('#' + jQuery(this).val()).show();
});
});
var selectBox = document.getElementById(id);
for(var i = 0, l = options.length; i < l; i++){
var option = options[i];
selectBox.options.add(new Option(option.text, option.value, option.selected));
}
jQuery("#"+id).html(jQuery("#"+id+" option").sort(function (a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}))
}
var placeOptions = [
{ "text" : "Text 1", "value" : "Text1" },
{ "text" : "Text 2", "value" : "Text2" }
];
addOptions('placelist', 'places', placeOptions);
var textOptions = [
{ "text" : "Place 1", "value" : "Place1" },
{ "text" : "Place 2", "value" : "Place2" }
];
addOptions('textlist', 'texts', textOptions);
关于javascript - 如何将两个具有相同功能的select html标签的两个JS结合起来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37136438/