Problem with jQuery edit-in-place with live() func

2019-07-24 01:43发布

问题:

This is probably an easy fix, but I am having trouble wrapping my brain around it...

I'm using a jQuery edit-in-place plugin for some divs that will be generated on the fly. It should be simple: Click in the newly created div, and be able to edit the contents. I'm running into problems with live().

Without using live(), it obviously works fine for a static div. Click once, get editable contents.

While using live(), however, I need to double click in order to edit the contents. Then any subsequent time it's clicked, it only takes once. It's sorta like a focus issue. Perhaps modifying the plugin itself would help?

Here is exactly what I'm talking about... http://jsfiddle.net/efflux/62CzU/

It has something to do with the way I'm calling the editinplace() function with live:

$('.editable').live('click',function() {
    //event.preventDefault();
    $('.editable').editInPlace({
        callback: function(unused, enteredText) { return enteredText; },
        bg_over: "#cff",
        field_type: "textarea",
        textarea_rows: "5",
        textarea_cols: "3",
        saving_image: "./images/ajax-loader.gif"
    });  
 });   

How can get the edit-in-place plugin to function normally on my divs created via js?

Any help would be appreciated!!

回答1:

Quick and dirty fix: http://jsfiddle.net/62CzU/5/

var $this = $(this),
      isInit = $this.data('edit-in-place');
if(!isInit){
    $('.editable').editInPlace({
        callback: function(unused, enteredText) { return enteredText; },
        bg_over: "#cff",
        field_type: "textarea",
        textarea_rows: "5",
        textarea_cols: "3",
        saving_image: "./images/ajax-loader.gif"
    });
    $this.click();
}


回答2:

It doesn't work because it's not set up until you click on it. Once you click on it, you set up the EditInPlace which requires it's own click. Just trigger another click after you set it up: http://jsfiddle.net/62CzU/6/



回答3:

Live Demo

Just change the buttons click to this.

$("button.btn").click(function() {
    $(".mydiv").prepend('<div class="passage-marker"><div class="annotation editable">it take 2 clicks to edit me, unless I have already been edited</div></div>');

         $('.editable').editInPlace({
            callback: function(unused, enteredText) { return enteredText; },
            bg_over: "#cff",
            field_type: "textarea",
            textarea_rows: "5",
            textarea_cols: "3",
            saving_image: "./images/ajax-loader.gif"
        });  

    });
}

Basically you are just rebinding it every time you create it. The reason you had an issue with live is because on the first click it bound it, so then on the second click it was already bound and would work.