使用jQuery更改Href后重置它



使用jQuery(或javascript(更改href后,如何重置它?

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

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

工作示例:

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

您可以将原始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>

最新更新