如何使用jQueryURI更新具有完整目录路径的链接

How do I update a link with a full directory path with jQuery URI?

本文关键字:路径 链接 jQueryURI 何使用 更新      更新时间:2023-09-26

我有一个函数,它的目的是更新通过jQuery.get()加载到页面中的HTML中的链接。后端应用程序有数千个链接,无法随时更新为包含完整路径,因此当转换到单页应用程序时,许多链接都是相对于/的,当它们需要包含完整路径时。

我在这里读到了几个关于从相对路径转换为绝对路径并找到绝对路径的问题,但它们不太适合我想要做的事情,而且我对Javascript和jQuery的理解仍然很弱,我不知道如何在这个症结之外寻找答案。

这是我的功能:

// handle modifying links, and attaching events
// href - The URL of the age that was loaded that triggered the handler callback
// target = left or right (must be ID, as # will be appended
var handler = function (data, href, target) {
  // Insert data into div
  $( '#' + target ).html(data);
  // Convert relative URLs in #right to include directory
  var base_path = URI(href).directory();
  $('#right a:uri(is: relative)').attr('href', base_path+'/'+$(this).href);
};

这成功地找到并添加了base_path(它从传递到函数中的href变量中获取),但我不知道如何在其中获取原始文件名和查询字符串。我没有定义。。。所以我显然不理解'$(this)'或.href。我尝试了许多其他选项来获取这些数据,但它们要么导致错误,要么导致未定义的值。。。再次表明我不知道自己在做什么。在谷歌上搜索"这个"很难。

我也试过使用$(this).attr('ref'),但结果是一样的。。。未定义。

简而言之:当我更新一个URI属性时,我如何在属性更新中找出最初选择的href并将其放入新的URI中?

注意,我使用的是jQuery和这个jQuery URI库:http://medialize.github.io/URI.js/jquery-uri-plugin.html

好吧,我通过一大堆谷歌搜索找到了这一点。我需要的功能是:

var handler = function (data, href, target) {
  // Insert data into div
  $( '#' + target ).html(data);
  console.log("href = ", href);
  // Convert relative URLs in #right to include directory
  var base_path = URI(href).directory();
  //var base_path = uri.directory() + '/';
  console.log(base_path);
  $('#right a:uri(is: relative)').each(function() {
    var cur_href = $(this).attr("href");
    $(this).attr("href", base_path+"/"+cur_href);
  });
};

更改是使用.each来允许匿名函数对每个相关链接进行处理。