點擊table中的td,修改td中的內容
前段時間,需要搭建演示頁面,有個功能是實現點擊表格中的某一格,能夠修改對應格子中的內容,一開始不知道怎么寫,在網上找了一下,自己再整合了一下,功能實現的代碼如下。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<title>Title</title>
</head>
<body>
<table border="1" class="setRecordStatus">
<tr>
<th>設備ID</th>
<th>設備通道號</th>
<th>實時播放地址</th>
</tr>
<tbody >
<tr >
<td class="deviceInfo">000001</td>
<td class="deviceInfo">000001</td>
<td class="deviceInfo">rtsp://192.168.1.2:554/stream1</td>
</tr>
</tbody>
</table>
<style type="text/css">
/**
* 把表格固定住,td長度固定,td中溢出的內容用...來代替
* */
table{
width: 600px;
table-layout:fixed;
}
td{
height: 30px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
</style>
<script type="text/javascript">
changeTableTd();
/**
*
* 添加鼠標點擊事件,可以改變table中表格的值
* */
function changeTableTd(){
// 獲取所有的單元格
td = document.getElementsByClassName("deviceInfo");
$(function () {
$(".deviceInfo").click(function () {
var index = $(this).index();
$(".setRecordStatus tr td").eq(index).html("");
var input = document.createElement("input");
input.type = "text";
input.style.width = "100%";
this.innerHTML = "";
this.appendChild(input);
input.focus();
input.onblur = function () {
$(".setRecordStatus tr td").eq(index).html(input.value);
console.log("輸入的值是" +input.value);
input.remove();
};
})
;
});
};
</script>
</body>
</html>
原始表格
點擊過后的表格
Tips
直接導入cdn的jquery的庫,所以代碼賦值粘貼下來可以直接進行功能展示。