3

私は値を持つ標準のhtmlラベルを持っています:

<label id="telefon" value="101"></label>

ラベルをクリックしてこの値を編集し、表示されたテキストボックスに新しい値を入力します(のようにvalue="202")。

どうすればそんなトリッキーなことをすることができますか?

私はJQuery関数で試しましたが、実際には機能しません:

$(function() {

  $('a.edit').on("click", function(e) {
    e.preventDefault();
    var dad = $(this).parent().parent();
    var lbl = dad.find('label');
    lbl.hide();
    dad.find('input[type="text"]').val(lbl.text()).show().focus();
  });

  $('input[type=text]').focusout(function() {
    var dad = $(this).parent();
    $(this).hide();
    dad.find('label').text(this.value).show();
  });

});
4

3 に答える 3

0

// フォーム タグにイベント リスナーを追加し、すべてのラベルに共通のハンドラーをコーディングできます ( Fiddle HERE )

// HTML

<form id="myform">
    <label style="background-color:#eee" title="101">Value is 101<label>
</form>

//JS

$(function(){
    $('#myform').on('click',function(e){
        var $label = $(e.target), $form = $(this), $editorInput = $('#editorInput'), offset = $label.offset();
        if($label.is('label')){
            if( !$editorInput.length){
                $editorInput = $('<input id="editorInput" type="text" value="" style="" />').insertAfter($label);
            }
            $editorInput.css('display','inline-block')
                .data('editingLabel', $label.get(0))
                .focus()
                .keydown(function(e){
                    var $l = $($(this).data('editingLabel')), $t = $(this);
                    if(e.which == 13){
                        $l  .attr('title', $t.val().replace(/(^\s+)|(\s+$)/g,''))
                            .text('value is now ' + $l.attr('title'));

                        // UPDATE YOUR DATABASE HERE

                        $t.off('keydown').css('display','none');
                        return false;
                    }
                });
        }
    });
});

// ちょっとした CSS

#editorInput{display:none;padding:2px;border:1px solid #eee;margin-left:5px}
于 2013-10-07T10:45:39.427 に答える