Program Tip

jQuery 객체 병합

programtip 2020. 11. 25. 08:19
반응형

jQuery 객체 병합


여러 jQuery DOM 객체를 하나의 배열로 병합하고 모든 객체에서 jQuery 메소드를 호출 할 수 있습니까?

F.ex :

<button>one</button>
<h3>two</h3>

<script>

var btn = $('button');
var h3 = $('h3');

$([btn,h3]).hide();

</script>

이것은 작동하지 않습니다. 여기에서 'button, h3'선택기를 사용할 수 있다는 것을 알고 있지만 일부 경우에는 이미 여러 개의 jQuery DOM 요소가 있고 이들 요소를 병합하여 모든 요소에서 jQuery 프로토 타입을 호출 할 수 있습니다.

같은 것 :

$.merge([btn,h3]).hide();

작동 할 것이다. 어떤 아이디어?

최신 정보:

해결했습니다. 다음과 같이 할 수 있습니다.

$.fn.add.call(btn,h3);

나는 add()올바른 방향으로 나를 가리키는 제안 을 받아 들일 것 입니다.


.add() 정확히 당신이 추구하는 것을합니다.

h3.add(btn).hide();

질문에서와 같은 "병합"기능을 사용하여 좀 더 편리하게 만들고 싶다면 다음과 같이 쉽게 추가 할 수 있습니다.

$.merge = function(objs) {
    var ret = objs.shift();
    while (objs.length) {
        ret.add(objs.shift());
    }
    return ret;
};

$.merge([h3, btn]).hide()

$.map 배열을 평면화 할 수 있습니다.

function merge(array_of_jquery_objects) {
    return $($.map(array_of_jquery_objects, function(el) {
        return el.get();
    }));
}

$(btn).add(h3).hide();

그래도 작동하는지 확실 하지 않은 추가 문서 에는 jQuery 객체를 매개 변수로 사용하는 것이 아니라 요소 목록 만 언급되어 있으므로 작동하지 않으면 다음과 같이해야합니다.

$(btn).add(h3.get()).hide();

jQuery 객체를 가져옵니다.

var x = $('script'),
    y = $('b'),
    z = $('body');

다른 모든 객체를 포함하는 새 jQuery 객체를 만듭니다.

$( $.map([x,y,z], a => [...a]) )

데모 : (브라우저 콘솔 열기)

var x = $('script'),
    y = $('b'),
    z = $('body');

// step 1
// put all the jQuery objects in an Array to prepare for step 2
var step1 = [x,y,z];
console.log(step1)

// using jQuery.map and a callback, extract  the actual selector from the iterable 
// array item and return it, so the result would be a simple array of DOM nodes
// http://jqapi.com/#p=jQuery.map
var step2 = $.map(step1, a => [...$.makeArray(a)])
console.log(step2);

// convert the javascript Array into jQuery Object (which contains all the nodes)
var step3 = $( step2 )
console.log(step3);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<b></b>


이것을 사용하십시오.

<script>

var btn = $('button')[0];
var h3 = $('h3')[0];

$([btn,h3]).hide();

</script>

참고 URL : https://stackoverflow.com/questions/1881716/merging-jquery-objects

반응형