0

「編集」ボタンを押してから「キャンセル」ボタンを押すと、jQueryコードに問題が発生しました。その後、もう一度「編集」を押すと、機能しません。

HTML

<div id="2">
<button class="edit" id="2">edit</button>
</div>

jQuery

$('.edit').click(function(){
        var id = $(this).attr('id');
        var post = $('div#'+id);
        var title = $('div#'+id+'>h1').html();
        var content = $('div#'+id+'>p').html();
        var edit = '<input type="text" class="title" id="'+id+'" value="title"><br>';
        var edit2 = '<textarea class="content" id="'+id+'" rows="10" cols="100">content</textarea>';
        $(this).remove();        
        post.append(edit);
        post.append(edit2);
        post.append('<br><button id="'+id+'" class="save">save</button><button id="'+id+'" class="cancel">cancel</button>');
        $('.cancel').click(function(){
            $('div#'+id+'>input').empty().remove();
            $('div#'+id+'>textarea').empty().remove();
            $(this).empty().remove();
            $('.save').empty().remove();
            $('div#'+id+'>br').remove();
            post.append('<button class="edit" id="'+id+'">Edit</button>');
        });
        /*$('.save').click(function(){
            var newTitle = $('input#'+id+'.title').val();
            var newContent = $('textarea#'+id+'.content').val();
            console.log(newTitle);
            console.log(newContent);
            console.log(id);
            $.post('/editPost', {id: id, title: newTitle, content: newContent}, function(){
                location.reload();
            });
        });*/
    });

jsfidde: http: //jsfiddle.net/pHCT8/2/

4

3 に答える 3

3

まず、2つの要素で同じIDを使用することはできません。これにより、ブラウザとJSのエラーが確実に発生します。

(また、HTML5 DOCTYPEを使用していない場合は、数字で始まるIDを使用しないでください)

次に、jQueryon()構文をライブハンドラーとして使用します。

$('#2').on('click','.edit', function(){

$('#2')開始点は、クリックリスナーを機能させる場所の外側の限界であることに注意してください。ワイドが必要な場合は、これを使用して、全身タグ内の$('body').on('click','.edit', function(){すべてのクリックをリッスンします.edit

理由は、クリックイベントハンドラーはDOMがロードされた要素に対してのみ機能しますが、ajax編集関数はロードされた(動的に作成された)ときにDOMになかった要素を作成するためです。

于 2012-12-08T00:18:09.397 に答える
1

実際にボタンを削除するのではなく、クリック時に.hideし、[キャンセル]をクリックしたときに.showを実行してみませんか?

http://jsfiddle.net/pHCT8/5/

変更された部分は次のとおりです。

$(this).hide();それよりも$(this).remove;

$('.edit').show();それよりもpost.append('<button class="edit" id="'+id+'">Edit</button>');

于 2012-12-08T00:21:05.037 に答える
1

ボタンを破棄して再作成する代わりに(この場合、イベントハンドラーが失われます)、ボタンを非表示/表示できます。

var self = $(this).hide();
...
$('.cancel').click(function(){
    ...
    self.show();

http://jsfiddle.net/mowglisanu/pHCT8/4/

于 2012-12-08T00:22:45.907 に答える