创建新表或更新表HTML

时间:2016-07-04 11:17:03

标签: javascript html

我有这个javascript,每次选择器更改值时都会创建一个新表。我希望它根据选择器的值更改行数,因此要么擦除最后一个表并创建一个新的或以某种方式更新。怎么办呢?

<script>
function tableCreate(){

var body = document.body,
    tbl  = document.createElement('table');
var rows = document.getElementById("numberOfCourses").value;

tbl.style.width  = '100px';
tbl.style.border = '1px solid black';

for(var i = 0; i < rows; i++){
    var tr = tbl.insertRow();
    var td = tr.insertCell();
    td.appendChild(document.createTextNode('Course ' + i));
}
body.appendChild(tbl);

}
document.getElementById("Course-info").innerHTML = tableCreate();
</script>

1 个答案:

答案 0 :(得分:0)

使用jquery,你的问题非常简单。 您可以在元素的行上使用jquery .hasClass()中的方法来检查类,然后相应地删除并创建新表或更新表。

您可以通过在html中包含身体末尾的以下链接来包含jquery。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">

代码:

if($('#id_of_the_row').hasClass("name_of_the_class")) {
    ...
} else {
    ...
}

现在,如果您想更新表记录,可以执行以下操作:

$('#id_of_the_row').html("your new html table row code");

要删除整个表并重新填充它,您可以通过抓取指向表的指针再次使用相同的方法,并使用.html()方法重写它。

我希望这会对你有所帮助。

相关问题