【问题标题】:How do I add a string value of an href using jquery?如何使用 jquery 添加 href 的字符串值?
【发布时间】:2011-04-30 01:30:21
【问题描述】:

我有一个带有 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();

【问题讨论】:

    标签: jquery input href


    【解决方案1】:
    $('#switch-fighter-search-button-link').attr("href","/fighters/search/" + $('$switch-fighter-text').val());
    

    【讨论】:

      【解决方案2】:

      试试这个:

      $('$switch-fighter-text').keyup(function(){
      
           $('#switch-fighter-search-button-link').get(0).href = 
                                                       "/fighters/search/"+this.value;
      
      });
      

      这将在搜索框更改时更新

      【讨论】:

        【解决方案3】:

        获取两个值并将它们连接起来(我猜是用 ? 分隔的),如下所示:

        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
        

        【讨论】:

        • 诚然,这可以用更少的行来完成(如达斯汀的例子),但我认为这样更容易阅读/理解。
        【解决方案4】:

        追加字符串。

        //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);
        });
        

        【讨论】:

          猜你喜欢
          • 2012-10-26
          • 1970-01-01
          • 2013-07-18
          • 1970-01-01
          • 2012-01-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多