简体   繁体   English

使用JavaScript将行插入表格

[英]Insert Rows to Table using Javascript

I am trying to add rows dynamically in my HTML table and its working fine. 我试图在我的HTML表中动态添加行,并且工作正常。 Now what I am trying to do is, I want to make them non-editable. 现在我想做的是,我想使它们不可编辑。 That is, once they are created, they should behave as normal <tr> <td> elements! 也就是说,一旦创建它们,它们就应该表现为普通的<tr> <td>元素! I tried assigning the readonly property after appending but it didn't work. 我尝试在附加后分配readonly属性,但是它不起作用。

The HTML HTML

<!DOCTYPE html>
<html>
<head>
<script src = "myScripts.js" type = "text/javascript"></script>

</head>
<body>


<table id="myTable" border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>

</table><br>

<button onclick="addRow()">Add Row</button>

</body>
</html>

the Javascript: Javascript:

var index = 1;
function addRow(){
            var table=document.getElementById("myTable");
            var row=table.insertRow(table.rows.length);
            var cell1=row.insertCell(0);
            var t1=document.createElement("input");
                t1.id = "txtName"+index;
                cell1.appendChild(t1);
            var cell2=row.insertCell(1);
            var t2=document.createElement("input");
                t2.id = "txtAge"+index;
                cell2.appendChild(t2);
        //t2.readonly = "readonly";
      index++;

}

使用setAttribute()方法。

inputElement.setAttribute('readonly',true);

JavaScript is case sensitive. JavaScript区分大小写。

t2.readOnly = true; t2.readOnly = true;

I will recommend the use of jQuery as it drastically reduces the lines of code. 我将推荐使用jQuery,因为它可以大大减少代码行。

I have used the readOnly attribute as below. 我使用了如下的readOnly属性。

Please see the Demo here 请在这里查看演示

HTML: HTML:

<table id="myTable" border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>

</table><br><button id="addRow">Add Row</button>

JS: JS:

var i=1;

$('#addRow').click(function(){   
    var appendString = "<tr><td><input type='text' id='txtName"+i+"' readonly='readonly' /></td><td><input type='text' id='txtAge"+i+"' readonly='readonly' /></td></tr>";

    $('#myTable tr:last').after(appendString);    
    i++;
});

See the code is reduced drastically. 看到代码大大减少了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM