获取特定点的URL(jQuery/JavaScript)

Get URL Up to a Specific Point (jQuery/JavaScript)

本文关键字:jQuery JavaScript URL 获取      更新时间:2023-09-26

我有一些用于语言选择的jQuery/JavaScript,它将获取URL,然后将相关的语言选择语法附加到其末尾。请看下面:

jQuery/JavaScript:

jQuery(document).ready(function() {
    var url = jQuery(location).attr('href') + '?___store=default&___from_store=default';
    jQuery(".english").attr("href", (url));
});

.HTML:

<div class="languageselection">
    <table>
        <tr>
          <td><a class="english">English</a></td>
        </tr>
    </table>
</div>

这很好用,可以满足我的需要,除非用户要选择一种语言,然后尝试移回另一种语言。这是因为?___store=default&___from_store=default被添加到 URL 上两次。生成以下 URL:

www.example.com/product.html?___store=default&___from_store=default?___store=default&___from_store=default

所以我的问题是是否可以修改我的 jQuery 变量,以便它只将 URL 获取到 URL 的.html点?这将导致语言语法只添加一次。

感谢您的任何帮助。

您可以使用

window.location.hostname + window.location.pathname来获得您想要的东西。请参阅位置对象:MDN

如果您需要获取当前网址。试试这个

 $(document).ready(function() {
//jquery
$(location).attr('href');
//pure javascript
var pathname = window.location.pathname;
// to show it in an alert window
alert(window.location);
});

在确定绝对路径时,此功能也可能会有所帮助。

function getAbsolutePath() {
var loc = window.location;
var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);
return loc.href.substring(0, loc.href.length - ((loc.pathname + loc.search + loc.hash).length - pathName.length));

}