Here is a plug-in that binds a click
event on an element, which generates a container with a <textarea>
and then i bind a keypress
event on this new <textarea>
, all is ok, but inside the keypress
handler i can only get the state of text().length
from when the initial click
happened.
How do i get the onKeyPress function to get the state of the <textarea>
at the time the keypress
happened?
$.fn.pluginTemp = function(options){
var defaults = {
editContainer:"<div class='editContainer'><textarea></textarea></div>",
maxChar:20,
onKeyPress:function(){
console.log($(".editContainer>textarea").text())
}
}
var options = $.extend(defaults,options);
return this.each(function(i,e){
var el = $(e)开发者_如何学运维, initText
el.bind("click", function(){
initText = el.text();
el.parent().append(options.editContainer);
el.parent().find(".editContainer>textarea").html(initText);
// isn't this function remembering the state for when its is defined? which is on keypress?
return function(){
el.parent().find(".editContainer>textarea").bind("keypress",options.onKeyPress)
}()
})
})
}
You could try:
return this.each(function(i,e){
var el = $(e), initText
el.live('click', function() {
initText = el.text();
el.parent().append(options.editContainer);
el.parent().find(".editContainer>textarea").html(initText);
// isn't this function remembering the state for when its is defined? which is on keypress?
return function(){
el.parent().find(".editContainer>textarea").bind("keypress",options.onKeyPress)
}()
})
})
Haven't tested as yet sorry
I got the problem,
Instead of getting the current value via the .html()
method,
I used .val()
Here is why:
The .html()
method when used on a <textarea>
looks only at the initial state of the textarea
, When you have .val()
it samples the most current value.
精彩评论