告诉我这个:
http://jsfiddle.net/TrySpace/QZMP6/17/
编辑输入字段后,每个元素的html更新,但我想重新启用/恢复点击事件..
我尝试将click事件作为外部函数,但我似乎无法让'this'正常工作/与函数通信...
似乎找不到如何将事件传递给函数的好解释......
正如你在小提琴中看到的那样,我试着这样做:
$(this).on("click");
但是当然它没有定义任何东西所以它不起作用,所以我将不得不重新调用/重新分配整个函数。?
答案 0 :(得分:1)
您可以将函数定义为变量。这样你就可以通过变量名称在click处理程序中引用它:
var clicky = function()
{
var currentClickedDIV = this.id;
$('#output').append("Clicked: "+currentClickedDIV +"<BR>");
var currentClickedDIVContent = $(this).html();
$('#output').append("HTML: "+currentClickedDIVContent +"<BR>" );
//Make current html content editable
$("#"+currentClickedDIV).html("<INPUT id='currentInput' value='"+currentClickedDIVContent+"'></INPUT>");
//prevent more triggers within element
$(this).off("click").on("click", function (e) {
e.stopPropagation();
});
//Focus cursor on input
$("#currentInput").focus();
var $that = $(this);
//On blur replace with plain html, also reenable click?
$("#currentInput").blur(function(){
var currInput = $("#currentInput").val();
$("#"+currentClickedDIV).html(currInput );
$('#output').append("New HTML: "+ currInput +"<BR>" );
$that.on("click", clicky);
});
return false;
}
$('.cuboid').on('click', clicky );
答案 1 :(得分:0)
演示:http://jsfiddle.net/QZMP6/23/
如果你改变了这个:
//Make current html content editable
$("#"+currentClickedDIV).html("<INPUT id='currentInput' value='"+currentClickedDIVContent+"'></INPUT>");
到此:
//Make current html content editable
$("#"+currentClickedDIV).html("<INPUT id='currentInput' value='"+currentClickedDIVContent+"'></INPUT>").children().on('blur', function () {
$('#' + currentClickedDIV).off('click').on('click', external_click);
});
在输入元素为blur
之后,将重新附加事件处理程序。另请注意,我将您的代码移动到名为external_click
的外部函数中。以下是上面发布的演示代码:
function external_click() {
var currentClickedDIV = this.id;
$('#output').append("Clicked: "+currentClickedDIV +"<BR>");
var currentClickedDIVContent = $(this).html();
$('#output').append("HTML: "+currentClickedDIVContent +"<BR>" );
//Make current html content editable
$("#"+currentClickedDIV).html("<INPUT id='currentInput' value='"+currentClickedDIVContent+"'></INPUT>").children().on('blur', function () {
$('#' + currentClickedDIV).off('click').on('click', external_click);
});
//Focus cursor on input
$("#currentInput").focus();
//On blur replace with plain html, also reenable click?
$("#currentInput").blur(function(){
var currInput = $("#currentInput").val();
$("#"+currentClickedDIV).html(currInput );
$('#output').append("New HTML: "+ currInput +"<BR>" );
});
//prevent more triggers within element
console.log($(this));
$(this).off("click").on("click", function (e) {
e.stopPropagation();
});
return false;
}
$('.cuboid').on('click', external_click);