如何获取现有的URL并将其用作jQuery中的链接,例如?
如果我的浏览器位于页面mysite.com/index.php?page=post&see=11
我希望在我的链接中使用网址,并在域名之后添加/new/
,如下所示:
<a href="mysite.com/new/index.php?page=post&see=11">link text</a>
答案 0 :(得分:0)
这将有助于您window.location...将URL作为字符串获取并使用它。找到&#34; .com /&#34;在字符串中,将其拆分,然后将两半连接到&#34; new /&#34;在中间。之后,您可以使用它来创建链接或导航到它......或者
<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>
答案 1 :(得分:0)
您可以使用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;
<小时/> 如果您想在网址的其他部分插入
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);
更新<a>
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>