Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

html - Move elements with jquery based on data attr with appendTo

What I need is that, when loading the site, move the li element into the ul element based on the datta attr. I did it, but for some reason, it doesn't work.

<li class="classeul_name" data-nivelpai="BR04ZJCTF000">Nivel 1</li>
<li class="classeul_name" data-nivelpai="BR055XCTF003">Nivel 2</li>

<ul data-geral1="BR04ZJCTF000">
</ul>

<ul data-geral1="BR055XCTF003">
</ul>

jQuery

  $(window).on("load", function(){
    // Joga o nível 2
    liName = $('.classeul_name').data('nivelpai');
    $('li[data-nivelpai="'+liName+'"]').appendTo($('ul[data-geral1="'+liName+'"]'));
  });
question from:https://stackoverflow.com/questions/66065724/move-elements-with-jquery-based-on-data-attr-with-appendto

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead on window load event you need to use the dom ready event:

$(function () { .... });

Moreover you need to loop on elements (i.e. .each()) and append() element.

The snippet:

$('.classeul_name').each(function(idx, ele) {
    var newPlace = '[data-geral1="' + ele.dataset.nivelpai + '"]';
    $(newPlace).append(ele)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<li class="classeul_name" data-nivelpai="BR04ZJCTF000">Nivel 1</li>
<li class="classeul_name" data-nivelpai="BR055XCTF003">Nivel 2</li>

<ul data-geral1="BR04ZJCTF000">
</ul>

<ul data-geral1="BR055XCTF003">
</ul>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...