2013-10-23 72 views
1

我正在動態創建無序列表,並通過單擊按鈕向其添加項目。我將其附加到contenteditable屬性設置爲true的部分。但是,我沒有看到它的工作。即使對於列表,我也將contenteditable屬性設置爲true,但我想它應該從它附加到的部分繼承。這是我正在做的事情的代碼。contenteditable不適用於動態生成的元素

// create text input 
var categoryInput = document.createElement('input') 
// create button to add the text entered to a list 
var btnAddToList = document.createElement('input'); 
btnAddToList.type ="button"; 
//create a section to add a list to 
var section = document.createElement('section'); 
var ul=document.createElement('ul'); 
section.appendChild(ul); 
section.contenteditable = "true"; 
ul.contenteditable = "true"; 
//create an event handler to add to the list 
if (btnAddToList.addEventListener) { btnAddToList.addEventListener('click', function() { addToList(ul, categoryInput.value);}); 
} else if (btnAddToList.attachEvent) { 
btnAddToList.addEvent('click', function() { addToList(ul, categoryInput.value);}); 

下面是函數我叫

function addToList(unorderedlist, inputText) { 

    if(inputText.length == 0) { 
     alert("Add Text"); 
     return; 
    } 


    var listitem = document.createElement('li'); 
    var listvalue = document.createTextNode(inputText); 
    listitem.appendChild(listvalue); 
    unorderedlist.appendChild(listitem); 
} 

什麼我做錯了還是沒做?任何幫助讚賞。由於

回答

2

您需要設置的屬性,而不是財產:

section.setAttribute('contenteditable', 'true'); 

而不是

section.contenteditable = "true"; 

一些更多的信息herehere(jQuery中的情況下,但涵蓋的話題漂漂儘管如此)。

我目前對差異的理解是屬性是可以通過標記(id,class,contenteditable等)設置的東西,而屬性是表示DOM節點的實際JavaScript對象的屬性。正如鏈接文章所提到的,這兩者通常由瀏覽器保持同步,但並非總是如此。

編輯: 正如Tim Down在他的回答中所述,雖然上述工作(設置屬性),但實際問題是屬性的名稱是錯誤的。它應該是

section.contentEditable = "true"; //Note the upper case 'E' 

設置屬性起作用的原因是屬性不區分大小寫。

+0

非常感謝。解決了它。唷!我現在得到了不同。 – user592748

+0

很高興我能幫到你。 – rusmus

+1

這不是問題所在。問題是這個屬性是'contentEditable'(注意大寫'E'),而不是'contenteditable'。該屬性必須與屬性保持同步,並且使用屬性而不是'setAttribute()'和'getAttribute()'幾乎總是一個更好的主意。 –

3

該物業是contentEditable(注意大寫'E'),而不是contenteditable

section.contentEditable = "true"; 
相關問題