0

次の関数を使用してページをロードしています。たくさんのリンクがあり、すべてのリンクに追加することはできません。

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

次のように、すべての<a>タグのhref値を取得し、この関数をすべてのリンクに追加する関数が必要です。

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++;
}

「INDEX.HTML」ではなく、すべてのリンクに追加したい。

4

2 に答える 2

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);
    }
});
于 2012-04-07T19:52:45.627 に答える
0

新しくロードされたページのリンクの変換に関する質問への回答として、@AnthonyGrist のような関数を新しいコンテンツに適用するために使用できるコールバック関数$.load()の 2 番目の引数を取ります。

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()することも合理的な解決策です。

于 2012-04-07T20:18:47.827 に答える