2012-06-15 4 views
2

페이지의 모든 앵커 태그를 얻고 mailto (예 : mailto:[email protected])에 하나의 클래스를 추가하고 다른 하나를 웹 링크 (예 : http://example.com)에 추가하는 방법은 무엇입니까? 예상페이지의 모든 앵커 태그를 얻고 클래스를 추가하는 방법은 무엇입니까?

출력 :

<a href="mailto:[email protected]" class="class1"> 
<a href="http://example.com" class="class2"> 
+1

당신이 뭘 했습니까 ?? –

+0

Pravat Maskey의 편집은 Sujeet의 원래 질문의 본질을 대폭 변경했습니다. 그게 뭐야? 편집이 OP가 실제로 요구 한 것을 반영하지 않기 때문에 나는 그것을 뒤로 굴리고있다. – HackedByChinese

답변

-1

$('a[href^="mailto:"]').addClass('class1'); 
$('a:not([href^="http:"])').addClass('class2'); 

처럼 iframe에 않습니다 찾을 않는 동일한 문서에 태그를 찾을 selecters에 대해 알고 도움이 될 것이다 like

jQuery("a[href^='mailto:']",jQuery("#myiframe")[0].contentDocument).addClass('class1'); 
jQuery("a:not([href^='http:'])",jQuery("#myiframe")[0].contentDocument).addClass('class2'); 
+0

당신은 CSS에서 그 속성 값 주위에 따옴표를 사용해야합니다 셀렉터 API를 사용하는 경우, 또는 지글 지글/jQuery를 일부 버전을 사용하는 경우 http://mothereff.in/unquoted-attributes#mailto%3A이 오류합니다. –

+0

이것은 OP가 실제로 요구 한 것이 아닙니다. – HackedByChinese

11
$('a[href^="mailto:"]').addClass('class1'); 
$('a:not([href^="mailto:"])').addClass('class2');​ 

예 : http://jsfiddle.net/HackedByChinese/3t2MQ/2/

업데이트 사용 :not() 대신 [href^="http"].

var elements = $("a"); 

:

$('a[href^="mailto').each(function(){ 
    $(this).addClass('sth') 
}) 
+2

CSS의 속성 값을 따옴표로 묶어야합니다. http://mothereff.in/unquoted-attributes#mailto%3A –

+0

@MathiasBynens 네, 고마워요. – HackedByChinese

0
$(document).ready(function() { 
    $.each($('a'), function(k, v) { 
     var href = $(v).attr('href'); 
     if (href.indexOf('mailto') != -1) 
      $(v).addClass('class1'); 
     else 
      $(v).addClass('class2'); 
    }); 
}); 
0

당신이 노력이

$('a[href^="mailto:"]').addClass('class1'); //This line adds a class to any href starting with mailto 
$('a[href^="http"]').addClass('class2'); //This line adds a class to any link starting with http 
+0

CSS의 속성 값을 따옴표로 묶어야합니다. http://mothereff.in/unquoted-attributes#mailto%3A Selectors API를 사용할 때 또는 일부 버전의 Sizzle/jQuery를 사용할 때 오류가 발생합니다. –

+0

그 대답은 이미 게시되었습니다 .. –

+1

@Learner 다른 포스터는 저에게 답을 쓰는 것을 끝내야 만합니다 ... 결론에 도달하지 마십시오. – Undefined

0

같은 것을 사용할 수 있습니다 거기에서 루프를 돌릴 수 있습니다. 시간 각각의 href를 값 확인 : 모든 앵커 요소를 통해 루프

elements.each(function(){ 
    var a = $(this); 
    if(a.attr("href").indexOf("mailto:") == 0){ 
     a.addClass("MailToClass"); 
    } 
    else{ 
     a.addClass("HttpClass"); 
    } 
}); 
+0

@downvoter 왜? – undefined

+1

실제로 이것은 아마도 가장 좋은 답변 일 것입니다. 하나는 – 11684

2

당신은 앵커 요소의 컬렉션을 얻기 위해이 JQuery와 사용할 수 있습니다

0

를 사용하여 jQuery를 .each() 기능을하고 href 이렇게 추가되는 클래스 알고 선택합니다.

$('a').each(function(){ 
    if($(this).attr('href') == 'mailto:[email protected]'){ 
     $(this).addClass('class1'); 
    } 
    else if($(this).attr('href') == 'http://example.com'){ 
     $(this).addClass('class2'); 
    } 
}); 
0
$("a").each(function(){ 
    if($(this).attr('href').indexOf('mailto:') == 0) {//mailto link 
    $(this).addClass('class1') 
    } 
    else { 
    $(this).addClass('class2') 
    } 
}); 
관련 문제