开发者

Problem with unique html() jQuery

I have jQuery function, that if it will hit specific class is wrapping it with some oter divs.

(document).ready(function(){
   var Text = $('.bd_box_cont').html();
   $('.bd_box_cont').html(" 
      <div class='bd_box_tl'><div class='bd_box_rt'>" + Text +"</div></div>

   ");
)}

Only problem is that I have more then one container on my site, and it is putting this same html to every one of them.

How can I return var Text fo开发者_运维知识库r specific container?

Thank you for your help in advance


You must pay more attention to the jquery selectors - http://docs.jquery.com/Selectors There are a lot of ways to get your object based on a filter.

$('.bd_box_cont:first').html
     ("       <div class='bd_box_tl'><div class='bd_box_rt'>" + Text +"</div></div>   
"); 

for example gets your first container


You use the class functions of jquery (so every div with the class bd_box_cont gets that html. When you only want one div to have that html, just use ids (#bd_box_cont).html... rest of you code.


You can do this more easily using .wrapInner():

$(document).ready(function(){
     $('.bd_box_cont').wrapInner("<div class='bd_box_tl'><div class='bd_box_rt'></div></div>');
});


Like @greg said use wrapInner(). For future reference, if you want to do something to each item of an element where one of the native functions won't suffice, use each():

$('.bd_box_cont').each(function() {
  this_element = $(this);
});


you could also use something like this (let's say you want to change i.e. second container):

var container = $('.bd_box_cont').get(1);
var Text = $(container).html();
$(container).html(" 
  <div class='bd_box_tl'><div class='bd_box_rt'>" + Text +"</div></div>
");

another option that does the same:

var container = $('.bd_box_cont:eq(1)');
var Text = container.html();
container.html(" 
  <div class='bd_box_tl'><div class='bd_box_rt'>" + Text +"</div></div>
");
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜