IT TIP

jQuery를 사용하여 일련의 div 요소 무작위 화

itqueen 2021. 1. 10. 19:45
반응형

jQuery를 사용하여 일련의 div 요소 무작위 화


jQuery로 첫 번째 단계를 수행하려고하는데 div 부모 요소에서 자식 요소 목록을 찾는 방법을 이해하는 데 약간의 문제가 있습니다. 저는 ActionScript 2와 ActionScript 3으로 작업하는 데 익숙해 져서 jQuery를 사용하여 div 요소 시퀀스를 무작위 화하는 더 좋은 방법과 같은 개념을 착각 할 수 있습니다!

HTML 코드의 간단한 부분이 있습니다.

<div class="band">
    <div class="member">
        <ul>
            <li>John</li>
            <li>Lennon</li>
        </ul>
    </div>
    <div class="member">
        <ul>
            <li>Paul</li>
            <li>McCartney</li>
        </ul>
    </div>
    <div class="member">
        <ul>
            <li>George</li>
            <li>Harrison</li>
        </ul>
    </div>
    <div class="member">
        <ul>
            <li>Ringo</li>
            <li>Starr</li>
        </ul>
    </div>
</div>

하나의 배열에서 map .member divs 와 같은 방법을 시도한 다음 정렬 순서를 변경했지만 성공하지 못했습니다.

function setArrayElements (element_parent) {
    var arr = [];
    //alert (element_parent[0].innerHTML);
    for (var i = 0; i < element_parent.children().length; i ++) {
        arr.push (element_parent[i].innerHTML);
    }
}
setArrayElements($(".band"));

내가 element_parent [0] 에게 경고하려고 할 때 .member div 목록의 첫 번째 자식을 얻으려고 생각 했지만 그렇지 않습니다.

element_parent [0] .innerHTML 로 알림을 보내면 다음 과 같이 표시됩니다.

<div class="member">
    <ul>
        <li>John</li>
        <li>Lennon</li>
    </ul>
</div>
<div class="member">
    <ul>
        <li>Paul</li>
        <li>McCartney</li>
    </ul>
</div>
<div class="member">
    <ul>
        <li>George</li>
        <li>Harrison</li>
    </ul>
</div>
<div class="member">
    <ul>
        <li>Ringo</li>
        <li>Starr</li>
    </ul>
</div>

왜? 이와 같은 회원 중 정확히 한 명을 얻으려면 어떻게해야합니까?

<div class="member">
    <ul>
        <li>Paul</li>
        <li>McCartney</li>
    </ul>
</div>

나는 이것이 쉬울 것이라고 확신하지만 방법을 모르겠습니다 :(


감사합니다
비토리오 도와주세요


편집하다:

견뢰와 선발 된 아이들을 얻을 수있는 다양한 방법에 감사드립니다. 앞으로도 이런 방법을 적어 볼게요!
이 방법을 시도했지만 전체 div를 얻을 수 없었던 것 같습니다 (내가 실수하면 너무 많이 가능할 수 있습니다 !!).

나는이 내용을 얻는다 :

<div class="member">
    <ul>
        <li>Ringo</li>
        <li>Starr</li>
    </ul>
</div>

그러나 $ ( "div.band div.member : eq (2)") 또는 다른 유용한 방법과 같은이 방법 중 하나를 사용하면 다음과 같은 결과를 얻을 수 있습니다.

alert ($('div.band div.member')[0]);
/* result
<ul>
    <li>Ringo</li>
    <li>Starr</li>
</ul>
*/

그래서 내 노드에서도 .member div 컨테이너 를 얻는 방법이 있습니까?


$('div.band div.member');

<div>선택기와 일치 하는 jQuery 객체를 제공합니다. 즉, div와 class member가있는 div의 자손 인 클래스가 band있습니다.

jQuery 객체는 일치하는 각 요소에 객체의 숫자 속성 (인덱스처럼 생각)이 할당되고 length속성도 정의 된다는 점에서 배열과 같은 객체입니다 . 하나의 요소를 얻으려면

// first element
$('div.band div.member')[0];

또는

// first element
$('div.band div.member').get(0);

모든 요소를 ​​선택하는 대신 DOM의 위치에 따라 특정 요소를 선택하도록 지정할 수 있습니다. 예를 들면

// get the first div with class member element
$("div.band div.member:eq(0)")

또는

// get the first div with class member element
$("div.band div.member:nth-child(1)")

편집하다:

방금 녹아웃 한 플러그인이 있습니다.

(function($) {

$.fn.randomize = function(childElem) {
  return this.each(function() {
      var $this = $(this);
      var elems = $this.children(childElem);

      elems.sort(function() { return (Math.round(Math.random())-0.5); });  

      $this.detach(childElem);  

      for(var i=0; i < elems.length; i++)
        $this.append(elems[i]);      

  });    
}
})(jQuery);

Here's a Working Demo. add /edit to the URL to see the code. If you need any details about how it works, please leave a comment. It could probably do with being made more robust to handle certain situations (like if there are other child elems of the jQuery object the plugin is chianed to) but it'll suit your needs.

Code from the demo

$(function() {

  $('button').click(function() {
    $("div.band").randomize("div.member");
  });

});

(function($) {

$.fn.randomize = function(childElem) {
  return this.each(function() {
      var $this = $(this);
      var elems = $this.children(childElem);

      elems.sort(function() { return (Math.round(Math.random())-0.5); });  

      $this.remove(childElem);  

      for(var i=0; i < elems.length; i++)
        $this.append(elems[i]);      

  });    
}
})(jQuery);

HTML

<div class="band">
    <div class="member">
        <ul>
            <li>John</li>
            <li>Lennon</li>
        </ul>
    </div>
    <div class="member">
        <ul>
            <li>Paul</li>
            <li>McCartney</li>
        </ul>
    </div>
    <div class="member">
        <ul>
            <li>George</li>
            <li>Harrison</li>
        </ul>
    </div>
    <div class="member">
        <ul>
            <li>Ringo</li>
            <li>Starr</li>
        </ul>
    </div>
</div>
<button>Randomize</button>

I modified Russ Cam's solution so that the selector is optional, and the function can be called on multiple container elements, while preserving each randomized element's parent.

For example, if I wanted to randomize all LIs within each '.member' div, I could call it like this:

$('.member').randomize('li');

I could also do it like this:

$('.member li').randomize();

So the two ways to call this are as follows:

$(parent_selector).randomize(child_selector);

OR

$(child_selector).randomize();

Here's the modified code:

$.fn.randomize = function(selector){
    (selector ? this.find(selector) : this).parent().each(function(){
        $(this).children(selector).sort(function(){
            return Math.random() - 0.5;
        }).detach().appendTo(this);
    });

    return this;
};

Minified:

$.fn.randomize=function(a){(a?this.find(a):this).parent().each(function(){$(this).children(a).sort(function(){return Math.random()-0.5}).detach().appendTo(this)});return this};

Randomization using sort does not always randomize the elements. It is better to use a shuffle method like the one from How can I shuffle an array?

Here's my updated code

(function($) {
    $.fn.randomize = function(childElem) {
        function shuffle(o) {
            for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
            return o;
        };
        return this.each(function() {
            var $this = $(this);
            var elems = $this.children(childElem);

            shuffle(elems);

            $this.detach(childElem);  

            for(var i=0; i < elems.length; i++) {
                $this.append(elems[i]);      
            }
        });    
    }
})(jQuery);

ReferenceURL : https://stackoverflow.com/questions/1533910/randomize-a-sequence-of-div-elements-with-jquery

반응형