2012-03-08 44 views
1

我試圖用JavaScript來行添加到動態使用下面的代碼表設置style.property到一個textarea:通過JavaScript

function addRowToTable() 
{ 
    var tbl = document.getElementById('targets'); 
    var lastRow = tbl.rows.length; 
    var iteration = lastRow; 
    var row = tbl.insertRow(lastRow);  

    var cellRight = row.insertCell(1); 
    var el = document.createElement('textarea'); 
    el.name = 'target' + iteration; 
    el.id = 'target' + iteration; 
    el.style.property="margin:4px; max-width:400px; width:400px; max-height:35px; height:35px;"; 
    cellRight.appendChild(el); 
} 

一切正常,除了el.style.property。我曾嘗試過el.style

這怎麼解決?

Here is the page (partially)

回答

4

使用style.cssText,而不是style.property

由於您的樣式看起來不變,考慮在樣式表存儲的樣式屬性,並使用類標識符添加的樣式:

<style> <!-- Inside the head --> 
.myclassname { 
    margin:4px; 
    max-width:400px; 
    width:400px; 
    max-height: 
    35px; height:35px; 
} 
</style> 

// Replace el.style.... with: 
el.className = 'myclassname'; 
0

單獨設置每個風格,即:

el.style.margin = "4px"

您標記了一個問題,jQuery的,所以你也可以使用這個符號是更好:

$(el).css({ 
    margin: "4px", 
    maxWidth: "400px", 
    width: "400px", 
    maxHeight: "35px", 
    height: "35px" 
}); 

話雖這麼說,如果你打算經常這樣做 - 你真的應該只是定義其這些屬性相匹配類:

.table-row { 
    margin: 4px; 
    max-width: 400px; 
    width: 400px; 
    max-height: 35px; 
    height: 35px; 
} 

,然後將該類添加到的元素。

// in JavaScript 
el.classList.add("table-row"); 

// in jQuery 
$(el).addClass("table-row");