2016-09-27 86 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元素的大小/樣式;如果您不喜歡默認外觀,則可以添加更多代碼來更改新元素的樣式。

相關問題