2013-07-30 5 views
-1

나는 예를 들어 링크의 몇 가지 그룹을 가지고 :각 그룹

<a href="http://google.com/b">http://google.com/b</a> 
<a href="http://google.com/a">http://google.com/a</a> 
<a href="http://stackoverflow.com/g">http://stackoverflow.com/g</a> 
<a href="http://google.com/c">http://google.com/c</a> 
<a href="http://stackoverflow.com/a">http://stackoverflow.com/a</a> 
<a href="http://en.wikipedia.org/c">http://en.wikipedia.org/c</a> 
<a href="http://en.wikipedia.org/a">http://en.wikipedia.org/a</a> 
<a href="http://en.wikipedia.org/b">http://en.wikipedia.org/b</a> 
내가 google.com 링크와 wikipedia.org 링크를 정렬하고 자신의 위치를 ​​유지해야

하지만 내 질문에 정렬에 대해하지 않습니다 . 요소 그룹에서 반복에 대한 내 질문. 예를 들면 다음과 같습니다.

$("a[href*='google.com'], a[href*='en.wikipedia.org']").each(function(){ 

    // I need in $(this) google.com links in first iteration, and wikipedia.org links in second 

}); 

고유 한 방법이 있습니까?

추신 : 포장은 불가능합니다. additional functions을 원하지 않습니다.

+0

그리고 무엇을 개선 당신은 HTML 후 *이 기능을 실행 *처럼 하시겠습니까? –

+0

첫 번째와 두 번째 반복이 혼란 스럽습니다. 그것을 반복하지 않을 것인가? 먼저 모든 Google 링크를 반복하고 싶다면 모든 위키 피 디아가 두 번째로 링크됩니다. 아마도 $ ("a [href * = 'google.com']"). add ("a [href * = 'en .wikipedia.org]]). 각자'나는 그것을 시도하지 않았다. –

+0

@Shredder 예. js 또는 jquery를 알고 싶습니다. 그룹과 반복 할 기본 방법이 있습니다. – hlcs

답변

2

그냥 도메인 당 그룹을 처리하려는 경우, 당신은 도메인을 반복하고 관련 요소를 찾을 수 있습니다 그리고

$.each(['google.com', 'en.wikipedia.org'], function (_, domain) { 
    var links = $('a[href*="' + domain + '"]'); 

    // 1st round will have `google.com` links, 2nd `en.wikipedia.org` 
}); 

단일 요소에 각 수집을 포장 .wrapAll()를 사용할 수 있습니다

links.wrapAll('<div>'); 

예 : http://jsfiddle.net/AmYCk/

<div> 
    <a href="http://google.com/b">http://google.com/b</a> 
    <a href="http://google.com/a">http://google.com/a</a> 
    <a href="http://google.com/c">http://google.com/c</a> 
</div> 

<a href="http://stackoverflow.com/g">http://stackoverflow.com/g</a> 
<a href="http://stackoverflow.com/a">http://stackoverflow.com/a</a> 

<div> 
    <a href="http://en.wikipedia.org/c">http://en.wikipedia.org/c</a> 
    <a href="http://en.wikipedia.org/a">http://en.wikipedia.org/a</a> 
    <a href="http://en.wikipedia.org/b">http://en.wikipedia.org/b</a> 
</div> 
+0

lol smart. 이 [http://jsfiddle.net/AmYCk/1/](http://jsfiddle.net/AmYCk/1/) exacly 내가 필요로하는,하지만 불행히도 그것은 hackish 더 원시처럼되지 않습니다. – hlcs

+1

@ancap 글쎄, JavaScript에는 고유 한 "* by group by *"함수 또는 메소드가 없습니다. jQuery는 일반적으로 포커스가 일반적으로 요소의 평면 집합이므로 하나를 정의하지 않습니다. 관심이 있으시면 [밑줄] (http://underscorejs.org/#groupBy) 또는 [lodash] (http://lodash.com/docs#groupBy)에서 찾을 수 있습니다. –

2

당신은 대신 다음을 사용할 수 있습니다

$('a[href*="google.com"]').add('a[href*="en.wikipedia.org"]').each(...); 

는 예를 들어이 jsFiddle를 참조하십시오.

+0

각 링크를 반복합니다. [http://jsfiddle.net/Z5rGf/](http://jsfiddle.net/Z5rGf/)]. google.com 및 위키 백과 링크 그룹이 아닙니다. – hlcs

+0

그러면 Jonathan Lonowski의 대답을 사용하고 싶을 것입니다. – Phylogenesis

0

버전

$([$("a"), $("span")]).each(function(){ 
    console.log($(this).length); 
}); 

jsbin.com