javascript - Wrapping and appending an array-element by using jQuery.each - Stack Overflow

I'm destroying myself over this. Not the must experienced ind js. But this should be simple right?

I'm destroying myself over this. Not the must experienced ind js. But this should be simple right?

I want to wrap each element in my 'arr'-array in <div class="mongol"></div> and append it to the div#testBox. Im using jQuery.each to do so, but I am not getting anything:

<script src=".3.1/jquery.min.js"></script>
<script type='text/javascript'>
  var arr = ["one", "two", "three", "four", "five"]

  jQuery.each(arr, function() {
    $(this).append("#testBox").wrap("<div class='mongol'></div>");
  });
</script>

I'm destroying myself over this. Not the must experienced ind js. But this should be simple right?

I want to wrap each element in my 'arr'-array in <div class="mongol"></div> and append it to the div#testBox. Im using jQuery.each to do so, but I am not getting anything:

<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type='text/javascript'>
  var arr = ["one", "two", "three", "four", "five"]

  jQuery.each(arr, function() {
    $(this).append("#testBox").wrap("<div class='mongol'></div>");
  });
</script>

If i alert(this) in my jQuery.each-function then it alerts every element just fine. I don't get it.

What i am trying to achieve:

<div id="testBox>
    	<div class=" mongol ">one</div>
    	<div class="mongol ">two</div>
    	<div class="mongol ">three</div>
    	<div class="mongol ">four</div>
    	<div class="mongol ">five</div>
    </div>

Share edited Apr 19, 2019 at 16:31 double-beep 5,51919 gold badges40 silver badges49 bronze badges asked Feb 15, 2011 at 13:00 Jonas ThomsenJonas Thomsen 1033 silver badges10 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

Are you confusing append() with appendTo()? The code you posted will append the testBox element to each of your array items, which is probably not what you want (and won't work anyway). Try:

jQuery.each(arr, function(index, item) {
    jQuery("<div class='mongol'></div>").text(item).appendTo("#testBox");
});
var arr = [ "one", "two", "three", "four", "five" ]
    jQuery.each(arr, function(index, value) {
    $("#testBox").append("<div class='mongol'>" + value + '</div>');
 });

That works if you have a <div> like that in your Site

<div id="testBox"></div>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743772122a4504563.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信