2012-04-07 2 views
0

다음 기능을 사용하여 페이지를로드하고 있습니다. 링크가 많아 모든 링크에 추가 할 수 없습니다. 나는 모든 링크에 추가 할 수 있지만에 "INDEXjquery를 통해 모든 링크에 함수를 추가하는 방법은 무엇입니까?

var oP = document.getElementsByTagName("a"), 
    ctr = 0 
; 

while(ctr < oP.length) { 
    var oldHref = document.getElementsByTagName("a")[ctr].href; 

    document.getElementsByTagName("a")[ctr].href = "javascript:loadPage('" + oldHref + "');"; 
    ctr++; 
} 

:

function LoadPage(url) { 
    $("#canvas").load(url); 
} 

나는 모든 <a> 태그를 href 가치를 그냥 다음과 같이 모든 링크에이 기능을 추가하는 기능을합니다. HTML ". 이 같은

+0

당신이 제공 한 일반 Javascript 코드에 대한 두 개의 주석 : 1.'document.getElementsByTagName ("a")가'oP'에 저장되어 있습니다.'while' 루프 내에서 다시 호출하는 것은 여분의 불필요한 처리입니다. 2. 다른 요소 컬렉션을 반복하는 것은 일반적으로 필요한 반복 횟수를 알고 있기 때문에'for' 루프가 아니라'for' 루프를 사용하여 수행됩니다. –

답변

2

뭔가 : 동적 페이지의 섹션을로드하는 때문에

// select all links 
$('a') 
    // check that the pathname component of href doesn't end with "/index.html" 
    .filter(function() { 
    return !this.href.pathname.match(/\/index\.html$/); 
    // // or you may want to filter out "/index.html" AND "/", e.g.: 
    // return !this.href.pathname.match(/\/(index\.html)?$/i) 
    }) 
    // add a click event handler that calls LoadPage and prevents following the link 
    .click(function(e) { 
    e.preventDefault(); 
    LoadPage(this.href); 
    }); 

대신 이벤트 위임을 설정해야합니다. 이 작업을 수행하는 방법은 사용중인 jQuery의 버전에 따라 다르지만, .on() (jQuery 1.7+) 또는 .delegate() (jQuery 1.7 이전) 함수를 사용하게됩니다. .on() 예는 다음과 같이 보일 것입니다 : 회신에서

$('body').on('click', 'a', function(e) { 
    if(!this.href.pathname.match(/\/index\.html$/)) { 
     e.preventDefault(); 
     LoadPage(this.href); 
    } 
}); 
+0

페이지를로드하고 있지만 새로로드 된 페이지의 링크를 변환하지 않습니다. 내가 새로로드 된 페이지에 대해해야 할 일은 무엇입니까? – danny

+0

에는 새로로드 된 페이지에도 해당 스크립트가 포함됩니다. –

+1

@danny 완전히 간과 했었습니다. 컨텐츠를 동적으로로드하기 때문에 이벤트 위임이 필요합니다. '.on()'을 사용하여 코드를 포함하도록 답변을 업데이트했습니다. 1.7 이전의 jQuery 버전을 사용하고 있다면'.delegate()'를 대신 사용해야합니다; 구문상의 차이는 상대적으로 작기 때문에 필요한 경우 링크 된 문서의 섹션을 읽어서 변환 할 수 있어야합니다. –

0

를 귀하의 질문에 당신이 @ AnthonyGrist 같은 함수를 적용하는 데 사용할 수있는 콜백 기능을 위해 새로로드 된 페이지, $.load() takes a second argument에 링크를 변환하는 방법에 대한 것은 새에의 콘텐츠 : 예 :

function loadPage(url) { 
    // add a callback to $.load() to be executed for the next content 
    $("#canvas").load(url, function() { convertLinks(this); }); 
} 

function convertLinks(context) { 
    // select all links in the given context 
    $('a', context) 
    // check that the pathname component of href doesn't end with "/index.html" 
    .filter(function() { 
     return !this.href.pathname.match(/\/index\.html$/); 
     // // or you may want to filter out "/index.html" AND "/", e.g.: 
     // return !this.href.pathname.match(/\/(index\.html)?$/i) 
    }) 
    // add a click event handler that calls LoadPage and prevents following the link 
    .click(function(e) { 
     e.preventDefault(); 
     loadPage(this.href); 
    }) 
    ; 
} 

// call convertLinks on the whole document on initial page load 
$(function() { convertLinks(document); }); 

.on()을 사용하는 것도 합리적인 해결책입니다.

+0

@Jorden 코드가 나를 놓치게됩니다.} 다시 확인해 주시겠습니까? – danny

+0

@ 대니 고정. 그것은 세 번째 줄에있었습니다. 일반적으로 스택 오버플로 (Stack Overflow) 응답의 코드는 복사 및 붙여 넣기가 아니라 일단 이해하면 스스로 이해하고 구현해야합니다. ;) –

+0

이 오류가 발생합니다. this.href.pathname은 정의되지 않았습니다. – danny

관련 문제