2016-11-08 1 views
4

내가 사용 jQuery를 다양한 파일 형식을 포함하는 링크를 목표로하고있다 : 첫째"a"태그를 선택하는 방법은 href에서 jQuery를 사용하여 특정 파일 형식을 갖고 있습니까?

jQuery('a[href$=".pdf"], a[href$=".doc"], a[href$=".docx"], a[href$=".ppt"], a[href$=".pptx"], a[href$=".xls"], a[href$=".slxs"], a[href$=".epub"], a[href$=".odp"], a[href$=".ods"], a[href$=".txt"], a[href$=".rtf"]').before('<span class="glyphicon glyphicon-file"></span> '); 

, 반복을 줄이는 방법은 무엇입니까? 예 :

jQuery('a[href$=".pdf|.doc|.docx"]) 

둘째, 파일 확장자에 대해 다른 경우를 타겟팅하는 방법이 있습니다. Pdf, PDFpdf?

답변

7

.filter()을 사용하여 선택한 요소를 필터링 할 수 있습니다. 필터 함수에서 String.prototype.match()에 regex를 사용하여 확장을 확인하십시오.

$("a").filter(function(){ 
    return $(this).attr("href").match(/\.(pdf|doc|docx|ppt|pptx|xls|slxs|epub|odp|ods|txt|rtf)$/i); 
}).before("Some html"); 

주 그 문자를 구분 정규식 일치 케이스의 끝에 i 플래그.

+0

당신을 감사 특수 문자를 지원해야하는 경우

function getEndsWithSelector(names) { return names.map(n => 'a[href$=".'+name+'"]').join(); } jQuery(getEndsWithSelector('pdf', 'txt', 'xls')) 

당신은 약간의 탈출을 추가해야합니다./\ 않습니다. 정규식에서 파일 확장자 만 대상으로합니까? – user2726041

+0

@ user2726041 아니요, 자바 스크립트에서 정규 표현식을 '//'사이에 설정해야합니다. 또한 '\ .' 일치하는 점. – Mohammad

0

단순히 CSS를 사용하는 것이 아니라 custom selector을 만들 수 있습니다.

jQuery.expr[':'].hrefEndsWith = function(
     objNode, 
     intStackIndex, 
     arrProperties, 
     arrNodeStack 
     ){ 
     // The list of arguments gets passed as a string - 
     var arrArguments = arrProperties.split(','); 
     // Create a jQuery version of this node. 
     var jThis = $(objNode); 
     // Check to see if this node ends with (we only need to find 
     // one of the titles to qualify). 
     for (var i = 0 ; i < arrArguments.length ; i++){ 
      // Check for title equality. 
      if (jThis.attr("href").endsWith(arrArguments[i])){ 
       // We found a href match, return true to 
       // indicate that this node should be included 
       // in the returned jQuery stack. 
       return true ; 
      } 
     } 
     // If we have made it this far, then we found no 
     // match. Return false to indicate that this node 
     // did not match our selector. 
     return false ; 
    } 

    // Use it 
    jQuery("a:hrefEndsWith('.pdf', '.txt', '.xls')"); 

아니면 그냥 선택기를 만들 수있는 JS 함수를 작성할 수 있습니다. 당신이 우수

관련 문제