JavaScript 将输入文本更改为 select 选项

JavaScript change input text to select option

是否可以使用 JavaScript 将页面上的元素从输入文本字段更改为 select 选项元素?

我想用 greasemonkey 自定义一些页面。

您需要识别表单和输入元素(通过名称或 ID)。您需要创建新的 select 元素,根据需要创建并添加任意数量的 option 元素,最后将其插入现有文本输入元素的位置。

例如,您可以使用如下内容:

// ** change 'form' and 'text' to correctly identify the form and text input element **
var inputElement = document.forms['form'].elements['text'];
var selectElement = document.createElement('select');

// get the existing input element's current (or initial) value
var currentValue = inputElement.value || inputElement.getAttribute('value');

// add a list of options to the new select element
// ** change value/text and add/remove options as needed **
var options = [{value: 'option1', text: 'Option 1'},
               {value: 'option2', text: 'Option 2'},
               {value: 'option3', text: 'Option 3'}];

options.forEach(function (option, i) {
    var optionElement = document.createElement('option');
    optionElement.appendChild(document.createTextNode(option.text));
    optionElement.setAttribute('value', option.value);
    selectElement.appendChild(optionElement);

    // if the option matches the existing input's value, select it
    if (option.value == currentValue) {
        selectElement.selectedIndex = i;
    }
});

// copy the existing input element's attributes to the new select element
for (var i = 0; i < inputElement.attributes.length; ++ i) {
    var attribute = inputElement.attributes[i];

    // type and value don't apply, so skip them
    // ** you might also want to skip style, or others -- modify as needed **
    if (attribute.name != 'type' && attribute.name != 'value') {
        selectElement.setAttribute(attribute.name, attribute.value);
    }
}

// finally, replace the old input element with the new select element
inputElement.parentElement.replaceChild(selectElement, inputElement);

如果它是一个没有附加很多脚本的普通表单元素,则相当简单。但是,请注意,如果有任何脚本事件附加到文本元素(焦点、更改、模糊等),这些将不再起作用。如果您希望 select 元素具有类似的脚本事件,则需要重新编写这些事件以应用到它。

新的 select 元素也可能与原来的 input 元素不同 size/style;如果您不喜欢默认外观,可以添加更多代码来更改新元素的样式。