Jquery重命名标签内的内容并确认它



用户应该能够更改名称,然后确认更改。我无法用此代码存档它,因为当我单击确认时,它会像以前一样返回。我错过了什么?

有更好的方法来把这些放在一起吗(我相信有一个)?

请查看演示,在那里您还可以看到changeElementType函数

http://jsfiddle.net/dLk6E/

js:

$('.replace').on('click', function () {
    $("h2").changeElementType("textarea");
    $('.replace').hide();
    $('.confirm').show();
    //Confermation of the change
    $('.confirm').bind('click', function () {
        $('.replace').show();
        $('.confirm').hide();
        $("textarea").changeElementType("h2");
    });

    if ($('textarea:visible')) {
        $(document).keypress(function (e) {
            if (e.which == 13) {
                alert('You pressed enter!');
                $("textarea").changeElementType("h2");
                $('.replace').css('opacity', '1');
            }
        });
    }
});

这是您更新的代码和工作小提琴http://jsfiddle.net/dLk6E/

(function($) {
    $.fn.changeElementType = function(newType) {
        var attrs = {};
        $.each(this[0].attributes, function(idx, attr) {
            attrs[attr.nodeName] = attr.nodeValue;
        });
        this.replaceWith(function() {
            return $("<" + newType + "/>", attrs).append($(this).contents());
        });
    }
})(jQuery);

$('.replace').on('click', function (){
    $("h2").changeElementType("textarea");
    $('.replace').hide();
    $('.confirm').show();
    //Confermation of the change
    $('.confirm').on('click', function(){
        $('.replace').show();
        $('.confirm').hide();
        // you are missing this
        $('.replaceble').html($("textarea").val());
        $("textarea").changeElementType("h2");
    });


    if ($('textarea:visible')){
         $(document).keypress(function(e) {
            if(e.which == 13) {
                alert('You pressed enter!');
                $("textarea").changeElementType("h2");
                $('.replace').css('opacity','1');
            }
        });
    }

});

jsfiddle.net/dLk6E/1

我认为你的代码是正确的,但你需要使用你在替换它时输入的值。因此,确认绑定应该是这样的(获取它,然后在将其"转换"为h2标签之前使用它来更新textarea)。

$('.confirm').bind('click', function(){
    var valueEntered = $('textarea').val();
    $('.replace').show();
    $('.confirm').hide();
    $("textarea").html(valueEntered).changeElementType("h2");
});

您可以使用。on, jQuery 1.7更倾向于使用。bind。

我建议的另一件事是,当你遇到类似的问题时只要在谷歌上输入你想要的,在这种情况下"jquery get value of input"会得到第一个结果jquery文档

这样你就不会忘记了;)

更新:也许是一个小细节,但在绑定中我使用它会更有效,只是点击$('textarea')一次,所以它会是这样的。您可能会记住(这里不是真正的问题),最好将其存储在变量中,而不是多次访问DOM。

$('.confirm').on('click', function(){
    var $textarea = $('textarea');
    $('.replace').show();
    $('.confirm').hide();
    $textarea.html($textarea.val()).changeElementType("h2");
});

jsfiddle

最新更新