从URL变量获取值并显示它

问题描述 投票:0回答:1

我正在尝试显示问候消息,后跟从URL中获取的名称值。它有效,但是如果没有变量名称,则甚至不会显示问候消息。可能导致此问题的原因是什么?

<h1 class="welcomeGreeting" style="color: white !important; text-align: center; padding-bottom:1px !important; margin-bottom:1px !important;">
</h1><script>
    var url = window.location.href;
    var captured = /name=([^&]+)/.exec(url)[1]; // Value is in [1] ('384' in our case)
    var result = captured ? captured : 'myDefaultValue';
//var result = window.location.href.split('&name=')[1];


  window.alert(result);
  var thehours = new Date().getHours();
 var themessage;
 var morning = ('Good morning');
 var afternoon = ('Good afternoon');
 var evening = ('Good evening');

 if (thehours >= 0 && thehours < 12) {
      themessage = afternoon + ' ' + result;

 } else if (thehours >= 12 && thehours < 17) {
      themessage = afternoon + ' ' + result;

 } else if (thehours >= 17 && thehours < 24) {
      themessage = afternoon + ' ' + result;
 }

 $('.welcomeGreeting').append(themessage);

</script>
javascript jquery dom domparser
1个回答
1
投票

它有效,但是如果没有变量名称,则甚至不会显示问候消息。可能导致此问题的原因是什么?

如果找不到匹配,exec将返回null。所以,当你在null[1]中不存在变量时,你正试图做url

您需要先在变量中取值,然后从中提取值

var captured = /name=([^&]+)/.exec(url);
var result = captured ? captured[1] : 'myDefaultValue';
© www.soinside.com 2019 - 2024. All rights reserved.