首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用jQuery更改Href后重置Href

使用jQuery更改Href后重置Href
EN

Stack Overflow用户
提问于 2021-04-28 06:37:03
回答 1查看 33关注 0票数 0

如何在使用jQuery (或javascript)更改href后将其重置?

我通过附加一个关键字来更改URL。但每次用户更改关键字或单击提交时,关键字都会被附加到最后一个URL。我希望新的关键字被添加到原来的网址只。

注意:我无法通过javascript访问原始URLs它们是使用WordPress (PHP/HTML/MySQL)创建的。

工作示例:

代码语言:javascript
运行
复制
(function($) {
  $( "button" ).click(function() {

    // Get and display user's keyword
    var inputVal = document.getElementById("keyword").value;
    document.getElementById('display-keyword').innerHTML = "keyword: " + inputVal;


    // For each external URL
    $( ".launch a" ).each(function() {

      var testAppURL = $( this ).attr("href"); // external URL
      var launchURL = testAppURL + inputVal;  // new external URL
        
      $( this ).attr("href", launchURL); // Set href to new external URL
      $( this ).html(launchURL);

    });
    
  });
})(jQuery);
代码语言:javascript
运行
复制
* {
  font-size: 1.2rem;
}

a {
  display: block;
}
代码语言:javascript
运行
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" placeholder="Enter a keyword" id="keyword">
<button type="button">Set Keyword</button>

<p id='display-keyword'>&nbsp;</p>

<div class="launch">
  <a href="https://www.example.com/" target="_blank" rel="noopener">Launch Me</a>
  <a href="https://www.websitenumb2.com/" target="_blank" rel="noopener">Launch Me</a>
</div>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-28 06:44:20

您可以将原始URL保存在数据属性中并恢复到该属性中:

代码语言:javascript
运行
复制
(function($) {
  $( "button" ).click(function() {

    // Get and display user's keyword
    var inputVal = document.getElementById("keyword").value;
    document.getElementById('display-keyword').innerHTML = "keyword: " + inputVal;


    // For each external URL
    $( ".launch a" ).each(function() {

      var testAppURL = $( this ).attr("href"); // external URL
      var launchURL = $( this ).attr("data-href") + inputVal;  // new external URL
        
      $( this ).attr("href", launchURL); // Set href to new external URL
      $( this ).html(launchURL);

    });
    
  });
})(jQuery);
代码语言:javascript
运行
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" placeholder="Enter a keyword" id="keyword">
<button type="button">Set Keyword</button>

<p id='display-keyword'>&nbsp;</p>

<div class="launch">
  <a href="https://www.example.com/" data-href="https://www.example.com/" target="_blank" rel="noopener">Launch Me</a>
  <a href="https://www.websitenumb2.com/" data-href="https://www.websitenumb2.com/" target="_blank" rel="noopener">Launch Me</a>
</div>

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67291509

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档