2017-01-11 41 views
-1

如何在JavaScript中複製以下內容? 我想在同一頁面中有兩個下拉菜單。Javascript - 查找並複製下拉列表

<fieldset id="product-options-wrapper" class="product-options"> 
    <dl class="last"> 
    <dt> 
    <label class="required"> 
    <em>*</em> 
    Pack Size/Price 
    </label> 
    </dt> 
    <dd class="last"> 
     <div class="input-box"> 
     <select id="attribute148" class="required-entry super-attribute-select" name="super_attribute[148]" onchange="return changeSku(148, this);"> 
      <option value="">Choose an Option...</option> 
      <option value="76">10g: €9.60</option> 
      <option value="61">25g: €17.40</option> 
      <option value="78">100g: €43.80</option> 
     </select> 
     </div> 
    </dd> 
    </dl> 

謝謝

+2

使用https://api.jquery.com/clone/ – rahulsm

+0

爲什麼要在一頁中選擇2個相同的選項?使用'.find()'與'.clone()' – guradio

+0

另外,刪除id並僅使用class或爲克隆的元素設置不同的id。 –

回答

1
var $select = document.querySelector('select#attribute148'); 
$select.id = "newId"; 
document.querySelector('yourNewDivId').appendChild($select); 

首先更新你的實際選擇JS。然後你更新id,最後把它加到你想要的div上。

編輯點評

你可以建立一個模板:

function createSelect(id, options){ 
    var $select = document.createElement('select'); 
    $select.id = id; 
    for(var i = 0; i < options.length; i++){ 
     var $option = document.createElement('option'); 
     $option.value = options[i].value; 
     $option.innerHTML = options[i].name; 
     $select.appendChild($option); 
    } 
    return $select; 
} 
var select = createSelect(48, [{value: 76, name: "10g: €9.60}, ...]); 
document.querySelector('target').appendChild(select); 
+0

這個ID不是靜態的,所以我們不能這樣 – Robert

+0

所以這個代碼不是靜態的那個attributeID和select選項不會是一樣的,你看到的是一個產品我有很多產品。 – Robert

+0

使用模板功能,您可以添加一個ID,您可以使用它。它完全個性化。 – DomeTune

0

可以使用cloneNode方法這一點。

var el = document.getElementById('product-options-wrapper'); 
var dupEl = el.cloneNode(); 

dupEl.id = "some-new-id"; 
document.getElementById('some-container').appendChild(dupEl); 

編輯:以飽滿的代碼示例

0

測試了這一點!

document.getElementById("product-options-wrapper").onclick = function(){ // when the fieldset is clicked 
    var clone = this.cloneNode(true); 
    this.appendChild(clone); // clone it and append to the last fieldset 
} 

當用戶點擊指定的fieldset,它會克隆它,並追加新的克隆,以前的。

你可以改變什麼新的克隆被附加到通過改變this.appendChild(clone)document.getElementById("yourid").appendChild(clone)

希望這有助於! :-)

+0

謝謝,但我需要的是複製該下拉列表,實際上作爲列表複製,我想要下拉選項和然後克隆它並在另一個div中列出。所以我不需要任何點擊事件 – Robert