从按钮 href 中删除站点名称,直到" ? "符号



我的网站上有以下按钮:

<a role="button" id="purchase" href="https://www.website.com/my-product/?add-to-cart=111&variation_id=115855/">

此按钮属于选择器,因此当用户选择另一个产品选项时,变化会动态变化。

例如,用户可以选择变体A、B、C

按钮变成这样:

For A - https://www.website.com/my-product/?add-to-cart=111&variation_id=115856/
For B - https://www.website.com/my-product/?add-to-cart=111&variation_id=115857/
For C - https://www.website.com/my-product/?add-to-cart=111&variation_id=115858/

我只想排除一切,直到">";按钮链接中的符号,当我悬停在它上时应该是这样的:

<a role="button" id="purchase" href="?add-to-cart=111&variation_id=115855/">

我试过这样的东西:

function removeSlug() {
var slugtest = document.getElementById("purchase").value;
text.split('?')[0];
}

但无济于事。不幸的是,我的js知识太差,无法了解问题所在。

提前谢谢。

您可以使用.setAttribute((和.getAttribute((加上array.pop((:

var slugtest = '?' + document.getElementById("purchase").getAttribute('href')
.split('?').pop();
document.getElementById("purchase").setAttribute('href', slugtest);
console.log(document.getElementById("purchase"));
<a role="button" id="purchase" href="https://www.website.com/my-product/?add-to-cart=111&variation_id=115855/">

另一种更改url的方法可以基于url接口:

// get the href value
var hreftext = document.getElementById("purchase").getAttribute('href');
// convert href to an URL and get the search property
var slugtest = new URL(hreftext).search;
document.getElementById("purchase").setAttribute('href', slugtest);
console.log(document.getElementById("purchase"));
<a role="button" id="purchase" href="https://www.website.com/my-product/?add-to-cart=111&variation_id=115855/">

您不应该使用document.getElementById("purchase").value,因为它不是一个输入字段,而是一个元素,您必须像这个一样使用.getAttribute("href")

var slugtest = document.getElementById("purchase").getAttribute("href");
console.log(slugtest.split("?")[1]);

你可以在下面的代码段中运行它:

<a role="button" id="purchase" href="https://www.website.com/my-product/?add-to-cart=111&variation_id=115855/">
<script>
var slugtest = document.getElementById("purchase").getAttribute("href");
console.log(slugtest.split("?")[1]);
</script>

我建议使用regex的解决方案。

function modifyLinkHref() {
var href = document.getElementById("purchase").getAttribute('href');
var newHref = href.replace(/(.*)(?.*)/g, "$2");
document.getElementById("purchase").setAttribute('href', newHref);
console.log(document.getElementById("purchase").getAttribute("href"));
}
modifyLinkHref();

Regex:

(.*)(?.*)

详细信息:

  • .*:第1组-在字符之前取任何字符
  • ?.*:第2组-字符后?,取任意字符

解释

演示

相关内容

最新更新