javascript - jQuery:编辑标签只能工作一次

标签 javascript jquery

我想做一个<p>标签可通过单击进行编辑。我的问题:它只能编辑一次。第二次单击后,我的控制台中收到一条错误消息。

请参阅此处的 fiddle :http://jsfiddle.net/LnD8d/1/

HTML:

<div id="profile_description"><p>Click to add description</p></div>

JAVASCRIPT:

function editDiv(element_to_be_edited, update_description) {
    var divHtml = element_to_be_edited.text();
    var editableText = $("<textarea />");
    editableText.val(divHtml);
    element_to_be_edited.replaceWith(editableText);
    editableText.focus();

    // setup the blur event for this new textarea
    editableText.on('blur', function() {

        var html = $(this).val();
        var viewableText = $("<p>");
        viewableText.html(html);
        $(this).replaceWith(viewableText);
        // setup the click event for this new div
        viewableText.click(editDiv);

        // if update_description=true, update description ...
        if (update_description == true) {
           console.log('description has been updated'); 
        }    
    });

} // /function editDiv();

    $(document).ready(function() {
        $('#profile_description p').on('click', function() {
            console.log('click on p tag');
            var element_to_be_edited = $(this);
            var update_description = true;
            editDiv(element_to_be_edited, update_description);          
        });
    });

谁能明白为什么标签只能编辑一次而不能在第二次点击时编辑吗?

最佳答案

您替换了 p,因此点击处理程序不再起作用。解决这个问题最简单的方法是使用事件委托(delegate)。更改文档内的事件处理程序声明准备

$('#profile_description').on('click', "p", function() {

Demo

关于javascript - jQuery:编辑标签只能工作一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24597263/

相关文章:

javascript - 通过映射到子 html 元素呈现响应数据...使用 React 和更新状态

javascript - 如何在 cefsharp 中捕获/监听 javascript 函数或事件

javascript - 邮件订阅成功弹出表单

javascript - jQuery:绑定(bind) "CTRL+A"仅选择特定区域

Javascript - 通过引用定义对象属性名称

javascript - Div 在被拖动时自动调整大小(jQuery UI)

javascript - 检索 DIV 的 id 失败

javascript - 使用此脚本或与之类似的脚本,如何创建搜索脚本来搜索对象?

javascript - 是否可以从 iframe 中检测到 window.close?

javascript - WordPress 主题使用 Jquery 移动对象