通过JavaScript将style.property设置为textarea

通过JavaScript将style.property设置为textarea,javascript,jquery,html,Javascript,Jquery,Html,我正在尝试使用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);

我正在尝试使用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

如何解决这个问题

使用而不是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';
使用而不是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';

您可以单独设置每个样式,即:

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");

您可以单独设置每个样式,即:

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");