开发者

Keeps Update All Text And Not the selected text in jQuery

I have the following code iam trying to make the text div under the image editable by using keyup and using .val() but iam having a problem when i click on another image and edit the textbox to update the new image text they all change.

$('.HeaderGifs').live('click', function() {
 var img_class = $(this).attr("class"); 
 var img_src = this.s开发者_开发百科rc;
  $('#img_prop').css("display","block");
  $('#pre_img').html("<img src='"+img_src+"'></img>");
  var image_sel_id = img_class.replace("HeaderGifs ", "")
 alert(image_sel_id);

    $('#alt_text').keyup(function() { 

    var alt_text = $(this).val(); 

    $('#text_'+image_sel_id).text(alt_text);

        });
}); 

Thank You


The problem is with every click you're binding a new keyup handler to #alt_text, so just .unbind() the previous handler, like this:

$('#alt_text').unbind('keyup').keyup(function() {
  $('#text_'+image_sel_id).text($(this).val());
});

Or, a bit more efficient, just make image_sel_id a variable that changes and bind the #alt_text handler once...and it'll always point to the current image:

var image_sel_id;
$('.HeaderGifs').live('click', function() {
  $('#img_prop').css("display","block");
  $('#pre_img').html("<img src='"+this.src+"'></img>");
  image_sel_id = this.className.replace("HeaderGifs ", "")
}); 
$('#alt_text').keyup(function() {
  if(!image_sel_id) return; //one hasn't been clicked yet 
  $('#text_'+image_sel_id).text($(this).val());
});

Note the check in the #alt_text handler, this is optional since #text_ probably won't find anything, but might as well save some cost and not run the rest of the function at all since an image hasn't been clicked yet.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜