【问题标题】:Get url & change it on click获取 url 并在点击时更改它
【发布时间】:2017-12-20 12:04:21
【问题描述】:

我想获取当前页面的 url (http://example.com/en-user/?1234) 并在按钮上单击将“en-user”更改为“hi-user”并转到该页面,因此 url 应该类似于“http://example.com/hi-user/?1234”。提前致谢。

【问题讨论】:

  • 你自己尝试过吗
  • Stackoverflow 不是免费的代码编写服务。展示你的尝试。

标签: javascript url


【解决方案1】:

很简单...在按钮上设置点击事件处理程序,获取位置,调整字符串,设置 URL。

// Get button reference
var btn = document.getElementById("btn");

// Set up click event handler
btn.addEventListener("click", function(){
  // Get current URL
  var url = window.location.href;

  console.log(url);

  // Change a portion of the string
  // Obviously, change the values to suit your needs.
  url = url.replace(".net", ".com");

  console.log(url);

  // Navigate to new URL
  window.location.href = url;

});
<button id="btn">Change URL</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-30
    • 1970-01-01
    • 2015-03-11
    相关资源
    最近更新 更多