我认为这是一个语法问题,但我似乎无法找到一个能够解答我所寻找的问题的问题。有很多......很接近。可能是绑定的东西,或者#34; apply"但是我无法弄清楚如何在这种情况下使用它们。
我有一个函数,当触发时,将一个跨度转换为一个输入,以便进行编辑。然后,当焦点关闭(模糊)时,将保存新文本。到目前为止,它完全符合我的要求。我认为如果输入键会做同样的事情会很好......但我无法弄清楚如何使事件发挥作用。
function span_into_textarea() {
var old_text = $(this).text();
var editableText = $("<input type='text' />");
editableText.val(old_text);
$(this).replaceWith(editableText);
editableText.focus();
editableText.blur(textarea_into_span);
editableText.keypress(function (e) {
if (e.which == 13) {textarea_into_span()}
}); // THIS DOESNT PASS ANYTHING TO "THIS"
editableText.keypress(textarea_into_span); //THIS WORKS BUT I CAN'T KNOW WHICH KEY WAS PRESSED
}
function textarea_into_span() {
var new_text = $(this).val();
}
感谢您的帮助!
答案 0 :(得分:2)
editableText.keypress( textarea_into_span.bind(this) )
(事件作为参数传递)。您可以将textarea_into_span
替换为arrow function(它们不绑定this
,以便在父上下文中查找它):
editableText.keypress( (e) => {
if (e.which == 13) {
var new_text = $(this).val();
}
})
editableText.keypress( function(e) {
if (e.which == 13) {
textarea_into_span.call(this);
// or textarea_into_span.apply(this)
}
})
答案 1 :(得分:2)
您可以使用call
传递this
参考:
editableText.keypress(function (e) {
if (e.which == 13) {textarea_into_span.call(this)} //will refer to editableText
});
答案 2 :(得分:1)
尝试这种方式,你失去了范围:
function span_into_textarea() {
var modify = this;
var old_text = $(this).text();
var editableText = $("<input type='text' />");
editableText.val(old_text);
$(this).replaceWith(editableText);
editableText.focus();
editableText.blur(textarea_into_span(modify));
editableText.keypress(function (e) {
if (e.which == 13) {textarea_into_span(modify)}
});
}
function textarea_into_span(modify) {
var new_text = $(modify).val();
}
答案 3 :(得分:0)
editableText.keypress(function(e) {
var key = e.which;
if (key == 13) // enter key ascii code
{
textarea_into_span.call(this) //will refer to editableText
}
});