简体   繁体   English

用 jQuery 更改后重置 Href

[英]Reset Href after changing it with jQuery

How can I reset an href after changing it using jQuery (or javascript)?使用 jQuery (或javascript)更改href后如何重置href?

I change the URL by appending a keyword.我通过附加关键字来更改 URL 。 But each time the user changes the keyword or clicks submit, the keyword keeps getting appended to the last URL.但是每次用户更改关键字或单击提交时,关键字都会不断附加到最后一个 URL 上。 I want new keywords to be added only to the original URL.我希望仅将新关键字添加到原始 URL 中。

Note: I do not have access to the original URLs via javascript - they are created using WordPress (PHP/HTML/MySQL).注意:我无法通过 javascript 访问原始 URL - 它们是使用 WordPress (PHP/HTML/MySQL) 创建的。

Working example:工作示例:

 (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);
 * { font-size: 1.2rem; } a { display: block; }
 <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>

You could save the original URL in a data attribute and restore to that:您可以将原始 URL 保存在数据属性中并恢复为:

 (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);
 <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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM