如何使用jquery添加href的字符串值?
我有一个带有href的输入按钮。我需要在输入文本框的href中的最后一个/后面添加一个字符串。如何使用jquery实现这一点?代码如下:如何使用jquery添加href的字符串值?,jquery,input,href,Jquery,Input,Href,我有一个带有href的输入按钮。我需要在输入文本框的href中的最后一个/后面添加一个字符串。如何使用jquery实现这一点?代码如下: //This is the Search Button $('#switch-fighter-search-button-link').attr("href","/fighters/search/"); //This is the Input box var sft = $('$switch-fighter-text').val(); 试试这个: $('$
//This is the Search Button
$('#switch-fighter-search-button-link').attr("href","/fighters/search/");
//This is the Input box
var sft = $('$switch-fighter-text').val();
试试这个:
$('$switch-fighter-text').keyup(function(){
$('#switch-fighter-search-button-link').get(0).href =
"/fighters/search/"+this.value;
});
这将在搜索框中更新更改抓取两个值并将它们连接起来(我猜是用?分隔的),如下所示:
$('#switch-fighter-search-button-link').attr("href","/fighters/search/" + $('$switch-fighter-text').val());
var head = $('#switch-fighter-search-button-link').attr("href"); // get existing href
var tail = $('#switch-fighter-text').val(); // get input value
var nhref = head + '?' + tail // join them together, separated by a ? character
$('#switch-fighter-search-button-link').attr('href', nhref); // update the button with the new href value
追加字符串
//save the base string somewhere at the beginning of your jquery
var basehref = $('#switch-fighter-search-button-link').attr("href","/fighters/search/");
//add a event handler when the text box is changed to update the button
$('#switch-fighter-text').change(function() {
var sft = basehref + $(this).val();
$('#switch-fighter-search-button-link').attr("href", sft);
});
诚然,这可以用更少的行完成(如Dustin的例子),但我认为这样读/读会更容易。