我尝试在默认情况下选择的页面上的每个下拉列表的顶部添加一个下拉菜单选项“请选择”,使用类似这样的内容:
window.onload = function() {
$('select option[value="PSC"]').attr("selected",true);
};
这就是我用于下拉列表的内容:
window.onload = function AddItem(text,value) {
// Create an Option object
var opt = document.createElement("option");
// Add an Option object to Drop Down/List Box
document.getElementsByTagName("option").options.add(opt);
// Assign text and value to Option object
opt.text = 'Please select...';
opt.value = 'Please Select';
}
我是javascript的新手,有人可以指出我正确的方向来编译这一点,以便当页面加载每个下拉列表时获得一个名为“请选择”的默认选择选项
先谢谢
答案 0 :(得分:1)
$(document).ready(function() {
$('<option>', {
text : 'Please select...',
value : 'Please select...',
selected : true
}).prependTo('select');
});
或者:
var select = document.getElementsByTagName("select"),
opt = '';
for (var i = 0; i < select.length; i++) {
opt = document.createElement("option");
// opt.selected = true;
opt.text = 'Please select...';
opt.value = 'Please Select';
select[i].options.add(opt);
}
答案 1 :(得分:1)
将纯javascript函数修改为此函数(这不会影响已选择的选项)DEMO jsfiddle
window.onload = function AddItem(text, value) {
// Get all Drop Down/List Box in document
var sel = document.getElementsByTagName("select");
for (var x = 0; x < sel.length; x++) {
// Create an Option object and set it's value/text
var opt = document.createElement("option");
opt.text = 'Please select...';
opt.value = 'Please Select';
//prepend in select box
sel[x].insertBefore(opt, sel[x].options[0])
}
}
答案 2 :(得分:0)
你走了:
$('select').prepend('<option>Please select...</option>');
答案 3 :(得分:0)
$(document).ready(function() {
$("select").prepend("<option value='' selected='selected'>Please select</option>");
});