新增<选项>到所有下拉列表< select>标签使用JavaScript

新增<选项>到所有下拉列表< select>标签使用JavaScript

问题描述:

我试图在页面上的每个下拉列表的顶部添加一个下拉菜单选项请选择,默认情况下会使用类似的方式来选择:

Im trying to add a Drop down menu option "Please select" to the top of each drop-down list on a page to be selected by default, using something similar like this:

window.onload = function() {
    $('select option[value="PSC"]').attr("selected",true);
};

这就是即时消息使用的下拉菜单:

and this is what im using for the drop-down:

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新手,有人能指出我正确的方向将它们编译在一起,以便当页面加载每个下拉列表时获得一个名为请选择的默认选择选项。

I'm new at javascript, can someone point me in the right direction to compiling this together so that when the page loads every drop-down list gets a default selected option called "Please select"

在此先感谢

Thanks in Advance

修改了您纯粹的javascript函数,以此函数(这不影响已经选择的选项) DEMO jsfiddle
$ b

Modified you pure javascript function to this function (This does not affect the already selected option) 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])
        }
     }