jQuery元素在dblclick/blur上跳跃

jQuery元素在dblclick/blur上跳跃,jquery,element,Jquery,Element,我编写了以下代码: HTML: JS: $(.hideCollapseQuestion”)。每个(函数() { $span=$(此项); $(此)。单击(函数() { var$questionChoices=$(this.parent().parent().children(“.questionChoices”); if($questionChoices.css(“display”)=“none”) $questionChoices.fadeIn(); 其他的 $questionChoices

我编写了以下代码:

HTML:

JS:

$(.hideCollapseQuestion”)。每个(函数()
{
$span=$(此项);
$(此)。单击(函数()
{
var$questionChoices=$(this.parent().parent().children(“.questionChoices”);
if($questionChoices.css(“display”)=“none”)
$questionChoices.fadeIn();
其他的
$questionChoices.fadeOut();
});
});
$(“.questionTitle”).each(函数()
{
$(this).dblclick(function()
{
关于问题标题更改($(本));
});
});
函数onQuestionTitleChange($title)
{
$currentTitle=$title.text();
$newInputField=$('');
$title.replace为($newInputField);
$newInputField.focus();
$newInputField.blur(函数()
{
$oldSpan=$(''+$newInputField.val()+'');
$newInputField.replaceWith($oldSpan);
$oldSpan.dblclick(函数()
{
问题标题变更($oldSpan);
});
});
}​
我的目标是使问题标题在双击时可编辑。开始时一切正常,但例如,如果编辑第一个问题,然后编辑第二个问题,如果要再次编辑第一个问题,则会用输入替换第二个范围[并非预期的第一个]


请注意,我不想为此使用现成的插件。

您正在替换已设置dbl click事件的问题标题。没关系,但最好正确使用jQuery的“.on”函数:

$(".question").on('dblclick', '.questionTitle', function()
{
    onQuestionTitleChange($(this));
});
这样,您就不必再向下重置事件处理程序。


我还建议您只改变字段的可见性,而不是一次又一次地重新创建它们…

只需在最后几行执行以下操作:

替换

$oldSpan.dblclick(function()
        {
            onQuestionTitleChange($oldSpan);    
        });

请看工作示例:

没错,谢谢。现在我看到我第一次做了相同的绑定dblClick:)即使这是错误,请参阅我的答案中的建议以改进代码。
$(".hideCollapseQuestion").each(function()
{
    $span = $(this);
    $(this).click(function()
    {
        var $questionChoices = $(this).parent().parent().children(".questionChoices");

        if ($questionChoices.css("display") === "none")
            $questionChoices.fadeIn();
        else
            $questionChoices.fadeOut();
    });
});

$(".questionTitle").each(function()
{
    $(this).dblclick(function()
    {
        onQuestionTitleChange($(this));
    });
});

function onQuestionTitleChange($title)
{
    $currentTitle = $title.text();
    $newInputField = $('<input type="text" value="' + $currentTitle + '" />');
    $title.replaceWith($newInputField);
    $newInputField.focus();

    $newInputField.blur(function()
    {
        $oldSpan = $('<span class="questionTitle">' + $newInputField.val() + '</span>');
        $newInputField.replaceWith($oldSpan);

        $oldSpan.dblclick(function()
        {
            onQuestionTitleChange($oldSpan);    
        });
    });
}​
$(".question").on('dblclick', '.questionTitle', function()
{
    onQuestionTitleChange($(this));
});
$oldSpan.dblclick(function()
        {
            onQuestionTitleChange($oldSpan);    
        });
$oldSpan.dblclick(function()
                        {
                            onQuestionTitleChange($(this));    
                        });