开发者

can I add div before elements which be added dynamically in future?

I have a drag drop elements facility. I want to add a div before any element, after it is dropped to the page. Is it possible ? I tried to do it using live, but number divs it adds are strange. For first time, it add one or two an开发者_JAVA百科d second time. it adds more than two. I'm trying this :

$('#PageContent > .textElementClass').live('dblclick', function(e) {
ElementWidth=$(e.target).width();
targetElement=$(e.target);
$(e.target).css({'display':'none'});
$(e.target).before('<div id="TextValue" style="'+ElementWidth+'"><textarea cols="50" rows="10">Edit Content</textarea><input type="button" value="Save" class="SaveContent"></div>');

$('.SaveContent').live('click', function(e){
 firstChild=$('#TextValue > textarea').html();
 $(targetElement).html(firstChild);
 $(targetElement).css({'display':'block'});
 $('#TextValue').remove();
});
   });


You need a few changes here, first is that IDs can't be used more than once in a page, so if you're dynamically adding something, it shouldn't include the same ID like you have with this:

<div id="TextValue">

But, you don't need an ID, you can simply fire the <textarea> that's in the <div> you clicked using tree-traversal to find it relative to what you clicked on, like this:

$(this).siblings("textarea").val();

This also uses .val() to get the value, use this instead of .html(). Also, you can use .show() and .hide() instead of setting the .css() manually.

When you're setting the style, it's ending up as style="40", which is invalid/has no effect...the <div> should stretch to the proper width, so I removed this piece. If it's needed, you can add it back via .width(valueToSet).

Last, you can use this in a .live() handler and your .live('click',...) should be outside your .live('dblclick',...), otherwise it's adding an additional save click handler every time you add an element, resulting in an additional save and remove each time.

Overall, it should look more like this:

$('#PageContent > .textElementClass').live('dblclick', function() {
  targetElement = $(this).hide()
                         .before('<div><textarea cols="50" rows="10">Edit Content</textarea><input type="button" value="Save" class="SaveContent"></div>');
});
$('.SaveContent').live('click', function(){
  var ta = $(this).siblings("textarea").remove();
  $(targetElement).html(ta.val()).show();
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜