2016-09-27 87 views
-5

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

我想用greasemonkey定制一些页面。

+0

是的,这是可能的。你试过了吗? –

+0

是的;有很多方法可以做到这一点。 SO并不是针对具体的实施问题。去尝试自己实现它,然后回来一个更具体的问题。 – Aeolingamenfel

+0

不,这是不可能的,你不能改变一个元素tagName,但你可以用另一个元素替换它。 – adeneo

回答

2

您需要识别表单和输入元素(通过名称或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元素的大小/样式;如果您不喜欢默认外观,则可以添加更多代码来更改新元素的样式。

相关问题