HTML 표 셀을 편집 가능하게 만드는 방법은 무엇입니까?
html 테이블의 일부 셀을 편집 가능하게 만들고 싶습니다. 셀을 두 번 클릭하고 텍스트를 입력하면 변경 사항이 서버로 전송 될 수 있습니다. dojo 데이터 그리드와 같은 툴킷을 사용하고 싶지 않습니다. 다른 기능을 제공하기 때문입니다. 구현 방법에 대한 코드 스 니펫이나 조언을 제공해 주시겠습니까?
해당 셀, 행 또는 표에서 contenteditable 속성을 사용할 수 있습니다.
IE8 호환성을 위해 업데이트 됨
<table>
<tr><td><div contenteditable>I'm editable</div></td><td><div contenteditable>I'm also editable</div></td></tr>
<tr><td>I'm not editable</td></tr>
</table>
테이블을 편집 가능하게 만들면 최소한 Mozilla에서 행을 삭제할 수 있습니다.
또한 타겟 고객의 브라우저가이 속성을 지원하는지 확인해야합니다.
변경 사항을 수신하는 한 (서버로 보낼 수 있도록) contenteditable 변경 이벤트를 참조하십시오.
HTML5는 contenteditable,
<table border="3">
<thead>
<tr>Heading 1</tr>
<tr>Heading 2</tr>
</thead>
<tbody>
<tr>
<td contenteditable='true'></td>
<td contenteditable='true'></td>
</tr>
<tr>
<td contenteditable='true'></td>
<td contenteditable='true'></td>
</tr>
</tbody>
</table>
타사 편집
contenteditable 에서 mdn 항목 을 인용하려면
속성은 다음 값 중 하나를 가져야합니다.
요소가 편집 가능해야 함을 나타내는 true 또는 빈 문자열입니다.
false, 요소를 편집 할 수 없어야 함을 나타냅니다.
이 속성이 설정되지 않은 경우 기본값은 상위 요소에서 상속됩니다.
이 속성은 부울 속성이 아니라 열거 속성입니다. 이는 true, false 또는 빈 문자열 중 하나의 명시 적 사용이 필수이며 속기 ...는 허용되지 않음을 의미합니다.
// wrong not allowed
<label contenteditable>Example Label</label>
// correct usage
<label contenteditable="true">Example Label</label>.
세 가지 접근 방식이 있습니다. 여기에서 둘 다 <input>
또는 <textarea>
요구 사항에 따라 사용할 수 있습니다 .
1.에서 입력을 사용 <td>
합니다.
<input>
모든 <td>
의 요소를 사용하여 ,
<tr><td><input type="text"></td>....</tr>
또한 입력 크기를 td
. 전의.,
input { width:100%; height:100%; }
편집 중이 아닐 때 입력 상자의 테두리 색상을 추가로 변경할 수 있습니다.
2. contenteditable='true'
속성을 사용 합니다. (HTML5)
그러나을 사용하려는 경우 contenteditable='true'
적절한 값을 데이터베이스에 저장할 수도 있습니다. ajax로 이것을 달성 할 수 있습니다.
당신은 keyhandlers을 첨부 할 수 있습니다 keyup
, keydown
, keypress
받는 사람 등 <td>
. 또한 사용자가 계속 입력 할 때 해당 이벤트와 함께 delay () 를 사용하는 것이 좋습니다 . 사용자가 키를 누를 때마다 ajax 이벤트가 실행되지는 않습니다. 예를 들면
$('table td').keyup(function() {
clearTimeout($.data(this, 'timer'));
var wait = setTimeout(saveData, 500); // delay after user types
$(this).data('timer', wait);
});
function saveData() {
// ... ajax ...
}
3. 클릭하면에 추가 <input>
합니다 <td>
.
의 입력 요소에 추가 td
이 때 <td>
클릭을 상기에 따라 그 값을 대체 td
의 값. 입력이 흐려지면`td '값을 입력 값으로 변경합니다. 이 모든 것이 자바 스크립트로.
이 코드를 사용해보십시오.
$(function () {
$("td").dblclick(function () {
var OriginalContent = $(this).text();
$(this).addClass("cellEditing");
$(this).html("<input type="text" value="" + OriginalContent + "" />");
$(this).children().first().focus();
$(this).children().first().keypress(function (e) {
if (e.which == 13) {
var newContent = $(this).val();
$(this).parent().text(newContent);
$(this).parent().removeClass("cellEditing");
}
});
$(this).children().first().blur(function(){
$(this).parent().text(OriginalContent);
$(this).parent().removeClass("cellEditing");
});
});
});
자세한 내용은이 링크를 방문 할 수도 있습니다.
x-editable https://vitalets.github.io/x-editable/ 부트 스트랩의 멋진 라이브러리를 사용할 수 있습니다.
Jquery를 사용하는 경우이 플러그인은 간단하지만 좋습니다.
https://github.com/samuelsantosdev/TableEdit
이것은 실행 가능한 단일 예제입니다.
<html>
<head>
<script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script> <!-- jQuery source -->
</head>
<body>
<table align="center">
<tr> <td>id</td> <td>name</td> </tr>
<tr> <td>001</td> <td>dog</td> </tr>
<tr> <td>002</td> <td>cat</td> </tr>
<tr> <td>003</td> <td>pig</td> </tr>
</table>
<script>
$(function(){
$("td").click(function(event){
if($(this).children("input").length > 0)
return false;
var tdObj = $(this);
var preText = tdObj.html();
var inputObj = $("<input type='text' />");
tdObj.html("");
inputObj.width(tdObj.width())
.height(tdObj.height())
.css({border:"0px",fontSize:"17px"})
.val(preText)
.appendTo(tdObj)
.trigger("focus")
.trigger("select");
inputObj.keyup(function(event){
if(13 == event.which) { // press ENTER-key
var text = $(this).val();
tdObj.html(text);
}
else if(27 == event.which) { // press ESC-key
tdObj.html(preText);
}
});
inputObj.click(function(){
return false;
});
});
});
</script>
</body>
</html>
셀 클릭시 동적으로 <input>
요소를 삽입 <td>
하십시오. 단순한 HTML과 자바 스크립트 만. 필요 없음에 contentEditable
, jquery
,HTML5
https://Jsfiddle.net/gsivanov/38tLqobw/2/
This is the essential point although you don't need to make the code this messy. Instead you could just iterate through all the <td>
and add the <input>
with the attributes and finally put in the values.
function edit(el) {
el.childNodes[0].removeAttribute("disabled");
el.childNodes[0].focus();
window.getSelection().removeAllRanges();
}
function disable(el) {
el.setAttribute("disabled","");
}
<table border>
<tr>
<td ondblclick="edit(this)"><input value="cell1" disabled onblur="disable(this)"></td>
<td ondblclick="edit(this)"><input value="cell2" disabled onblur="disable(this)"></td>
<td ondblclick="edit(this)"><input value="cell3" disabled onblur="disable(this)"></td>
<td ondblclick="edit(this)"><input value="so forth..." disabled onblur="disable(this)">
</td>
</tr>
</table>
this is actually so straight forward, this is my HTML, jQuery sample.. and it works like a charm, I build all the code using an online json data sample. cheers
<< HTML >>
<table id="myTable"></table>
<< jQuery >>
<script>
var url = 'http://jsonplaceholder.typicode.com/posts';
var currentEditedIndex = -1;
$(document).ready(function () {
$.getJSON(url,
function (json) {
var tr;
tr = $('<tr/>');
tr.append("<td>ID</td>");
tr.append("<td>userId</td>");
tr.append("<td>title</td>");
tr.append("<td>body</td>");
tr.append("<td>edit</td>");
$('#myTable').append(tr);
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + json[i].id + "</td>");
tr.append("<td>" + json[i].userId + "</td>");
tr.append("<td>" + json[i].title + "</td>");
tr.append("<td>" + json[i].body + "</td>");
tr.append("<td><input type='button' value='edit' id='edit' onclick='myfunc(" + i + ")' /></td>");
$('#myTable').append(tr);
}
});
});
function myfunc(rowindex) {
rowindex++;
console.log(currentEditedIndex)
if (currentEditedIndex != -1) { //not first time to click
cancelClick(rowindex)
}
else {
cancelClick(currentEditedIndex)
}
currentEditedIndex = rowindex; //update the global variable to current edit location
//get cells values
var cell1 = ($("#myTable tr:eq(" + (rowindex) + ") td:eq(0)").text());
var cell2 = ($("#myTable tr:eq(" + (rowindex) + ") td:eq(1)").text());
var cell3 = ($("#myTable tr:eq(" + (rowindex) + ") td:eq(2)").text());
var cell4 = ($("#myTable tr:eq(" + (rowindex) + ") td:eq(3)").text());
//remove text from previous click
//add a cancel button
$("#myTable tr:eq(" + (rowindex) + ") td:eq(4)").append(" <input type='button' onclick='cancelClick("+rowindex+")' id='cancelBtn' value='Cancel' />");
$("#myTable tr:eq(" + (rowindex) + ") td:eq(4)").css("width", "200");
//make it a text box
$("#myTable tr:eq(" + (rowindex) + ") td:eq(0)").html(" <input type='text' id='mycustomid' value='" + cell1 + "' style='width:30px' />");
$("#myTable tr:eq(" + (rowindex) + ") td:eq(1)").html(" <input type='text' id='mycustomuserId' value='" + cell2 + "' style='width:30px' />");
$("#myTable tr:eq(" + (rowindex) + ") td:eq(2)").html(" <input type='text' id='mycustomtitle' value='" + cell3 + "' style='width:130px' />");
$("#myTable tr:eq(" + (rowindex) + ") td:eq(3)").html(" <input type='text' id='mycustomedit' value='" + cell4 + "' style='width:400px' />");
}
//on cancel, remove the controls and remove the cancel btn
function cancelClick(indx)
{
//console.log('edit is at row>> rowindex:' + currentEditedIndex);
indx = currentEditedIndex;
var cell1 = ($("#myTable #mycustomid").val());
var cell2 = ($("#myTable #mycustomuserId").val());
var cell3 = ($("#myTable #mycustomtitle").val());
var cell4 = ($("#myTable #mycustomedit").val());
$("#myTable tr:eq(" + (indx) + ") td:eq(0)").html(cell1);
$("#myTable tr:eq(" + (indx) + ") td:eq(1)").html(cell2);
$("#myTable tr:eq(" + (indx) + ") td:eq(2)").html(cell3);
$("#myTable tr:eq(" + (indx) + ") td:eq(3)").html(cell4);
$("#myTable tr:eq(" + (indx) + ") td:eq(4)").find('#cancelBtn').remove();
}
</script>
참고URL : https://stackoverflow.com/questions/6012823/how-to-make-html-table-cell-editable
'developer tip' 카테고리의 다른 글
ASP.NET MVC Razor 모델을 레이아웃으로 전달 (0) | 2020.09.09 |
---|---|
'git push origin master'에서 'origin'의 의미는 무엇입니까? (0) | 2020.09.09 |
C ++에서 두 문자열을 연결하는 방법은 무엇입니까? (0) | 2020.09.09 |
목록 내에서 고유 한 값을 계산하는 방법 (0) | 2020.09.08 |
Mac에 jmeter를 어떻게 설치합니까? (0) | 2020.09.08 |