如何通过jquery在所有链接中添加函数

How to add function in all links through jquery?

本文关键字:链接 添加 函数 何通过 jquery      更新时间:2023-09-26

我正在使用以下函数来加载页面。我有很多链接,无法添加到所有链接。

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

我想添加到所有链接,但不添加到"索引.HTML"。

像这样:

// 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);
    }
});

在回答您关于在新加载的页面上转换链接的问题时,$.load()为回调函数提供了第二个参数,您可以使用该参数将像@AnthonyGrist这样的函数应用于新内容,例如:

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()也是一个合理的解决方案。