问题
I'm trying to make Jeditable works on new elements created using this jquery file tree.
On right click on a folder or file a context menu is shown and after clicking "Rename" item on the context menu i want to activate Jeditable.
I'm using this context menu and this code:
$(document).ready( function() {
$('#filetree').fileTree({
root: '../../../',
script: './connectors/jqueryFileTree.php',
expandSpeed: 1000,
collapseSpeed: 1000,
multiFolder: true
}, function(file) {
alert(file);
});
$.contextMenu({
selector: 'ul.jqueryFileTree > li',
callback: function(key, options) {
var m = "clicked: " + key;
window.console && console.log(m);
if(key == 'rename'){
$('#1').trigger("edit1");
}
},
items: {
"rename": {name: "Rename", icon: "edit", accesskey: "r"},
"cut": {name: "Cut", icon: "cut", accesskey: "c"},
// first unused character is taken (here: o)
"copy": {name: "Copy", icon: "copy", accesskey: "c o p y"},
// words are truncated to their first letter (here: p)
"paste": {name: "Paste", icon: "paste", accesskey: "cool paste"},
"delete": {name: "Delete", icon: "delete"},
}
});
/* Bind Jeditable instances to "edit" event. */
$("#1").editable("http://www.example.com/save.php", {
event: 'edit1',
});
});
});
But doesn't work, i've read on the web (here)that i should use .live (.on() is ok? since i'm using jquery 1.7.1) but i don't know why, can you help me?
回答1:
you can use .on() in place of .live() which works sort of like the .delegate() method. live is bit expensive as it keep track of the DOM changes and for that it has to iterate where as the .on()
or .delegate()
simply delagate the event to a higher element like document
or the body
.
$('.editableItem').live('click', function(){
$(this).editable("http://www.example.com/save.php", {
event: 'edit1',
});
});
Why you have to use live?
Because dynamically inserted elements into the DOM dont get attached to the event handlers automatically for that you have to use live
or upon insertion of elements you can manually bind the elements to the event handlers by using .bind()
here are some useful questions
Difference between jQuery `click`, `bind`, `live`, `delegate`, `trigger` and `on` functions (with an example)?
Jquery live() vs delegate()
http://paulirish.com/2010/on-jquery-live/
来源:https://stackoverflow.com/questions/8285344/making-jeditable-working-on-new-elements