在“输入”上,使输入元素在单元格中消失,但保留文本内容
On "enter" make input element dissapear in the cell, but leave the text content
我想用javascript更改单元格内容。当我单击一个单元格时,会出现一个input
元素,该元素获取单元格文本的值。当我单击输入时编辑输入元素中的文本后,我希望单元格再次正常(没有输入元素)。
下表如下:
<table>
<tr>
<td>Content 1</td>
<td>Content 2</td>
<td>Content 3</td>
</tr>
<tr>
<td>Content 4</td>
<td>Content 5</td>
<td>Content 6</td>
</tr>
</table>
这是Javascript:
$("td").click(function(){
if($(this).find("input").length==0){
var cellContent = $(this).html();
$(this).empty();
$(this).append("<input type='text' size='"+cellContent.length+"' value='"+cellContent+"'>");
$(this).find("input").focus();
}});// this part creates input element in a cell
现在,当新内容应保留在单元格中但没有输入元素时,按回车键后出现问题。
$("td").click(function(){
var newCellContent = $("input",this).val();
console.log(newCellContent);
$("input").keyup(function(event){
if(event.which == 13){
$(this).empty();
$(this).html(newCellContent);
}
newCellContent = $("input",this).val();
});
});
我个人建议使用 CSS 来显示/隐藏<input>
元素,并使用 JavaScript 仅处理值的传输和按 Enter 时<input>
的模糊,如下所示:
// finding the <table> element containing the <input> elements,
// and adding an event-listener:
document.querySelector('table').addEventListener('keyup', function(e) {
// 'e' is the event itself.
// caching the element that triggered the keyup event:
var current = e.target,
// caching its tagName, in lower-case:
tag = current.tagName.toLowerCase(),
// we're using this check twice, so caching the result,
// checking that the tag is equal to 'input', and that
// the element has a 'type' property, and that the
// current type is equal to 'text':
isRelevantInput = tag === 'input' && current.type && current.type === 'text';
// if the check returns true, and the key pressed (e.which) is
// equal to 13 (the enter key):
if (isRelevantInput && e.which === 13) {
// we blur the element (allowing the CSS
// to show the <label> text again, and hide
// the <input>:
current.blur();
}
// otherwise, if only the check itself is true
// (note that the most difficult-to-satisfy condition
// goes first):
else if (isRelevantInput) {
// we update the textContent of the <input> element's
// next element-sibling (the <span> in this example)
// to the current value of the <input> element:
current.nextElementSibling.textContent = current.value;
}
});
// Using Function.prototype.call() to use Array.prototype.forEach()
// to iterate over the NodeList returned from
// document.querySelectorAll():
Array.prototype.forEach.call(document.querySelectorAll('table label > input'), function (input) {
// the first argument of the anonymous function (here: 'input')
// is the array-element of the array over which we're iterating.
// setting the value of the <input> to the textContent of
// of its next element-sibling (the <span> containing the
// text of the parent <label> associated with the <input>:
input.value = input.nextElementSibling.textContent;
});
上面的 JavaScript 与这个 CSS 相结合:
td {
height: 2em;
}
label > input {
/* we're not using 'display: none' in
order that the <input> elements can
receive focus: */
opacity: 0;
height: 0;
}
/* once focused the <input>
has a defined height and
a visible opacity: */
label > input:focus {
opacity: 1;
height: 1.5em;
}
/* forcing the <span> to the
next line of the <td>: */
label > input + span {
display: block;
height: 1.5em;
}
/* hiding the <span> when the
<input> has focus: */
label > input:focus + span {
display: none;
}
对于 HTML:
<table>
<tr>
<td>
<!-- wrapping the <input> in a <label> element
means that clicking the <label> text will
focus the <input>, using CSS to show the
<input> and hide the <span>: -->
<label>
<input type="text" /><span>Content 1</span>
</label>
</td>
<!-- repeated content removed for brevity -->
</tr>
</table>
document.querySelector('table').addEventListener('keyup', function(e) {
var current = e.target,
tag = current.tagName.toLowerCase(),
isRelevantInput = tag === 'input' && current.type && current.type === 'text';
if (isRelevantInput && e.which === 13) {
current.blur();
}
else if (isRelevantInput) {
current.nextElementSibling.textContent = current.value;
}
});
Array.prototype.forEach.call(document.querySelectorAll('table label > input'), function (input) {
input.value = input.nextElementSibling.textContent;
});
td {
height: 2em;
}
label > input {
opacity: 0;
height: 0;
}
label > input:focus {
opacity: 1;
height: 1.5em;
}
label > input + span {
display: block;
height: 1.5em;
}
label > input:focus + span {
display: none;
}
<table>
<tr>
<td>
<label>
<input type="text" /><span>Content 1</span>
</label>
</td>
<td>
<label>
<input type="text" /><span>Content 2</span>
</label>
</td>
<td>
<label>
<input type="text" /><span>Content 3</span>
</label>
</td>
</tr>
<tr>
<td>
<label>
<input type="text" /><span>Content 4</span>
</label>
</td>
<td>
<label>
<input type="text" /><span>Content 5</span>
</label>
</td>
<td>
<label>
<input type="text" /><span>Content 6</span>
</label>
</td>
</tr>
</table>
但是,使用您当前的 HTML 并使用 jQuery,我建议:
// finding the relevant <td> elements,
// using on() to attach an anonymous
// click event-handler:
$('table td').on('click', function() {
// creating an <input> element,
// setting its 'type' and 'value'
// properties:
var input = $('<input />', {
'type': 'text',
'value': this.textContent
// appending the created <input> to the <td> (this/$(this))
// after emptying the <td> using empty(), and focusing the
// created <input>:
}).appendTo($(this).empty()).focus();
// binding an keyup event-handler using on(),
// passing the event ('e') to the function:
}).on('keyup', function(e) {
// if it was the enter key that was pressed:
if (e.which === 13) {
// finding the <input> element with find(),
// and caching the result:
var input = $(this).find('input');
// inserting the text string of the current
// value of the <input> before the <input>,
// and then removing the <input>:
input.before(input.val()).remove();
}
});
$('table td').on('click', function() {
var input = $('<input />', {
'type': 'text',
'value': this.textContent
}).appendTo($(this).empty()).focus();
}).on('keyup', function(e) {
if (e.which === 13) {
var input = $(this).find('input');
input.before(input.val()).remove();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Content 1</td>
<td>Content 2</td>
<td>Content 3</td>
</tr>
<tr>
<td>Content 4</td>
<td>Content 5</td>
<td>Content 6</td>
</tr>
</table>
引用:
- .CSS:
- 相邻同级(
+
)组合子。 - 子(
>
)组合器。 -
:focus
伪类。
- 相邻同级(
- .HTML:
-
<input>
. -
<label>
. -
<span>
.
-
- JavaScript:
-
Array.prototype.forEach()
. -
document.querySelector()
. -
document.querySelectorAll()
. -
eventTarget.addEventListener()
. -
Function.prototype.call()
. -
KeyboardEvent.key
.
-
- j查询:
-
appendTo()
. -
before()
. -
empty()
. -
find()
. -
remove()
. -
val()
.
-
这是你必须做的
$(function(){
$("table td").on('click',function(){
if($(this).find("input").length==0){
var cellContent = $(this).html();
$(this).empty();
$(this).append("<input type='text' size='"+cellContent.length+"' value='"+cellContent+"'>");
$(this).find("input").focus();
}
});
注意:在keyup
函数中使用td Object
之前,我如何先将存储在变量中。此外,您还需要使用remove()
函数来删除元素。
var newCellContent = $("input",this).val();
var tdObject = $(this);
====
====================================================================== $('table td').on('keyup',function(){
var newCellContent = $("input",this).val();
var tdObject = $(this); //Storing the td object in a variable
$("table td input").keyup(function(event){
if (event.keyCode == 13) {
console.log($(this).val());
$(this).remove(); // remove() removes an html element in this case input elem
tdObject.html(newCellContent);
}
newCellContent = $("input",this).val();
});
});
});
查看小提琴链接
您的参考资料:
jQuery DOCS remove()
我会尝试识别不同的任务并为其分配功能(addInput()
添加一个输入,removeInputs()
删除任何以前打开的输入)。试试吧:
var shownInputs = [];
$("td").click(function () {
if (!$(this).find("input").length) {
removeInputs();
addInput($(this));
}
});
function addInput(el) {
var cellContent = el.html();
el.html("<input type='text' size='" + cellContent.length + "' value='" + cellContent + "'>");
el.find("input").focus().keyup(function (e) {
var keycode = e.keyCode ? e.keyCode : e.which;
if (keycode == 13) {
removeInputs();
}
});
shownInputs.push(el);
}
function removeInputs() {
$.each(shownInputs, function (i, el) {
el.html(el.find("input").val());
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table>
<tr>
<td>Content 1</td>
<td>Content 2</td>
<td>Content 3</td>
</tr>
<tr>
<td>Content 4</td>
<td>Content 5</td>
<td>Content 6</td>
</tr>
</table>
创建input
后立即在第一个单元格click
处理程序中注册keyup
处理程序:
$("td").click(function(){
if($(this).find("input").length==0){
var cellContent = $(this).html();
$(this).empty();
$(this).append("<input type='text' size='"+cellContent.length+"' value='"+cellContent+"'>");
$(this).find("input").focus();
// > Added
$(this).find("input").keyup(function(event){
if(event.which == 13){
var newCellContent = $(this).val();
$(this).parent().html(newCellContent);
$(this).remove();
}
}).focus();
//
}});// this part creates input element in a cell
查看演示
小提琴链接 - 试试吧。下面的代码
您不需要多次单击绑定
$("td").click(function () {
if ($(this).find("input").length === 0) {
var cellContent = $(this).html();
$(this).empty();
$(this).append("<input type='text' size='" + cellContent.length + "' value='" + cellContent + "'>");
$(this).find("input").focus();
}
currentTd = $(this);
$("input").keydown(function (event) {
if (event.which == 13) {
$(this).remove();
$(currentTd).html($(this).val());
}
});
});
在$("input").keyup(function(event){}
中使用$(this)
会将函数(如.empty()
)应用于输入。
您可以通过多种方式解决此问题:
- 请改用
$(this).closest('td').empty()
:这将查找要应用函数的父"td"。 - 创建一个包含
td
元素的变量,并使用它来应用于函数。
另外:使用 .html()
设置 html 将覆盖当前内容,因此无需执行.empty()
。
示例代码(也清理了一点):
jQuery().ready(function(){
$("td").click(function(){
if($(this).find("input").length==0){
var cellContent = $(this).html();
$(this).empty();
$(this).append("<input type='text' size='"+cellContent.length+"' value='"+cellContent+"'>");
$(this).find("input").focus().keyup(function(event){
if(event.which == 13){
$(this).closest("td").html($(this).val());
}
});
}});// this part creates input element in a cell
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>Content 1</td>
<td>Content 2</td>
<td>Content 3</td>
</tr>
<tr>
<td>Content 4</td>
<td>Content 5</td>
<td>Content 6</td>
</tr>
</table>
你在错误的范围内做你的逻辑,本质上是针对输入。以下内容现在应该可以工作了。
$("td").click(function(){
var newCellContent = $("input",this).val();
console.log(newCellContent); $("input").keyup(function(event){
if(event.which == 13){
$(this).parent().empty();
$(this).parent().html(newCellContent);
}
newCellContent = $("input",this).val();
});
});
因为你keyup
事件绑定到动态创建的元素(inputs
),所以你必须在body
上使用on
函数
$("td").click(function(){
if($(this).find("input").length==0){
var cellContent = $(this).html();
$(this).empty();
$(this).append("<input type='text' size='"+cellContent.length+"' value='"+cellContent+"'>");
$(this).find("input").focus();
}});// this part creates input element in a cell
$('body').on('keyup', 'input', function(event) { // code
if(event.keyCode == 13){
$(this).parent( "td" ).html($(this).val());
}
});
这是适合您的
工作演示https://jsfiddle.net/o2ka4qnb/
- 当设置addFromAutocompleteOnly时,剩余文本将保留在输入字段中
- 单击其他元素或鼠标向上时隐藏输入框,但保留一次焦点
- 获取所有输入字段并保留文本字段中的值,即使在使用 javascript 和 php 提交按钮后也是如此
- 我在添加更多输入字段时遇到问题,文本字段中的值不会保留
- 使用onclick()时,在输入中保留必需的标记
- 添加一些值,以便在用户更改该服务器时将其作为占位符输入并保留它
- 使用 Java 脚本或 PHP 提交后保留输入框的最后一个值
- 如何将按钮/输入保留在图像下方
- 如何保留输入复选框值的存储数组
- jQuery clone() 将用户数据保留在输入字段中
- 如何在 AJAX 请求 (Rails) 之间保留表单输入数据
- 键入时保留占位符的文本输入
- 为什么新创建的输入标签不会保留在页面上
- 如何在验证失败弹簧 MVC 时保留输入表单值
- 当我克隆文件输入时,克隆的输入不会保留上传的文件.原始输入确实如此
- 清除 html 输入保留后退(ctrl+z)
- 如何在页面刷新后保留输入单选按钮的状态
- 更改属性文本并使用挖空保留输入的值
- 表单文本字段默认在焦点处消失,用户输入保留在表单更正处
- 将用户输入保留在浏览器中,而不绑定到Bean