如何在使用jQuery (或javascript)更改href后将其重置?
我通过附加一个关键字来更改URL。但每次用户更改关键字或单击提交时,关键字都会被附加到最后一个URL。我希望新的关键字被添加到原来的网址只。
注意:我无法通过javascript访问原始URLs它们是使用WordPress (PHP/HTML/MySQL)创建的。
工作示例:
(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'> </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>
发布于 2021-04-28 06:44:20
您可以将原始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'> </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>
https://stackoverflow.com/questions/67291509
复制相似问题