【问题标题】:How can I get existing URL and use as link in jQuery? [duplicate]如何获取现有 URL 并在 jQuery 中用作链接? [复制]
【发布时间】:2018-07-16 12:10:19
【问题描述】:

如何获取现有 URL 并在 jQuery 中用作链接,例如?

如果我的浏览器在页面mysite.com/index.php?page=post&see=11 我想在我的链接中使用 URL 并在域名后添加/new/,如下所示:

<a href="mysite.com/new/index.php?page=post&see=11">link text</a>

【问题讨论】:

  • stackoverflow.com/help/how-to-ask - 我们是来提供帮助的,而不是为您编写代码。向我们展示您迄今为止的尝试,我们将帮助您找出错误。但实际上没有人会为您编写代码。如果您不向我们展示解决您问题的任何努力,我们也不会这样做。
  • jquery 需要它
  • 这将帮助您window.location... 您可以将 URL 作为字符串获取并使用它...
  • DIEGO CARRASCAL 它获得了完整的网址,我该如何更改它
  • “我该如何改变它”是什么意思?您的问题没有说明将 URL 更改为其他任何内容

标签: javascript php jquery


【解决方案1】:

您可以使用window.location

window.location.pathname //returns the path (only);
window.location.href //returns the full URL; and
window.location.hostname //returns the domain name of the web host.

然后,你可以这样使用它:

var url = window.location.hostname + 'new/' + window.location.pathname;


如果要在 URL 的另一部分插入new,可以使用.split().splice().join()

var newUrl = window.location.href.split('/'); //create one array element at every /
newUrl.splice(3, 0, 'new'); //insert 'new' in the position 3
newUrl = newUrl.join('/'); //join every array element with '/' in a string

console.log(newUrl);

更新&lt;a&gt;href

var url = 'mysite.com/index.php?page=post&see=11';

//with javascript
var jsBtn = document.getElementById('jsBtn'); //get the <a> with id 'jsBtn'
jsBtn.setAttribute('href', addNew(url)); //set the attribute 'href' with the new one

//with jQuery
var jqBtn = $('#jqBtn'); //get the <a> with id 'jqBtn'
jqBtn.attr('href', addNew(url)); //change the 'href' attribute with the new url

//function to add 'new' to the array of strings (created with the url string)
function addNew (link){
    var newUrl = link.split('/'); 
    newUrl.splice(1, 0, 'new'); 
    newUrl = newUrl.join('/');
    return newUrl;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a id="jsBtn" href="#">javascript anchor</a>

<hr>

<a id="jqBtn" href="#">jQuery anchor</a>

【讨论】:

  • 但是我该怎么做这个代码只工作一个 href 我的链接
  • id 添加到此&lt;a&gt;。然后你可以使用 jQuery .attr(),或者 javascript .setAttribute()
  • 请展示示例
  • 检查更新的答案。 :)
【解决方案2】:

这将帮助您window.location... 您可以将 URL 作为字符串获取并使用它。在字符串中找到“.com/”,将其拆分,然后将两半与中间的“new/”连接起来。之后,您可以使用它来创建链接或导航到它......或者做

<a id="newLink" href="#" id="demo">my link</a> 
<script> 
  $(document).ready(function(){
   var newURL = window.location.hostname.toString();
   newURL = newURL + "new/";
   newURL = newURL + window.location.pathname.toString(); 
   $("#newLink").attr("href", newURL);  
  });
</script>

【讨论】:

  • 这是正确的吗? 我的链接
  • 几乎正确,您需要将href 更新为newURL 的值。如果您使用 jQuery:$('#demo').attr('href', newURL);
  • 我怎样才能只将它用于我的链接
  • 请提供我不理解的完整示例
  • 你不能。更新href 的唯一方法是使用 Javascript。 Javascript 必须有某种方式找到预期的&lt;a&gt; 标签;拥有id 属性是一种(好)方法。
猜你喜欢
  • 2012-10-08
  • 2021-08-15
  • 2016-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多