【问题标题】:Dropdown selected with URL parameter使用 URL 参数选择的下拉列表
【发布时间】:2015-04-16 17:32:26
【问题描述】:

如何使用 url 参数选择我的下拉菜单? 我找到了这个: Dropdown selected based on URL parameter - PHP or jQuery?

但这对我不起作用。我究竟做错了什么? 我的网址是:

kontakt.php?Betreff=3

脚本:

var val = location.href.match(/[?&]Betreff=(.*?)[$&]/)[1];   // get params from URL
$('#Betreff').val(val);   //  assign URL param to select field

和:

<select class="mailstyle" name="Betreff" id="Betreff">
    <option value="1">First</option>
    <option value="2">Second</option>
    <option value="3">Third</option>
</select>

【问题讨论】:

  • 你的意思是你不能看到optionvalue 等于3 被选中?
  • 是的,总是选择值 1!
  • 该正则表达式仅在您有多个参数时才有效,例如http://example.com/Betreff=3&amp;Inhalt=something

标签: javascript php jquery url-parameters


【解决方案1】:

试试这个:

$('#Betreff option').each(function(){
    if($(this).val()==val){
        $(this).attr("selected","selected");
        break; 
    }
});

【讨论】:

  • 感谢您的努力!但 Rory McCrossan 的答案正是我想要的!
【解决方案2】:

试试这个:

var val = location.href.match(/[?&]Betreff=(.*?)(?:$|&)/)[1];   // get params from URL
$('#Betreff').val(val);   //  assign URL param to select field

【讨论】:

    【解决方案3】:

    您的正则表达式不正确。可以使用这个函数(from this question)来获取参数值:

    function getURLParameter(name) {
        return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
    }
    

    然后您可以使用它来设置值:

    var val = getURLParameter('Betreff');
    $('#Betreff').val(val);   //  assign URL param to select field
    

    【讨论】:

      猜你喜欢
      • 2014-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-16
      • 1970-01-01
      • 1970-01-01
      • 2022-07-21
      相关资源
      最近更新 更多