【问题标题】:getting value from URL variable and displaying it从 URL 变量中获取值并显示它
【发布时间】:2017-12-27 05:59:39
【问题描述】:

我正在尝试显示一条问候消息,后跟从 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】:

它可以工作,但是如果没有变量名,甚至什么都不会显示 问候语。什么可能导致此问题?

exec 将返回 null 如果没有找到匹配。因此,当url 中不存在变量时,您尝试执行null[1]

你需要先取一个变量中的值,然后从中提取值

var captured = /name=([^&]+)/.exec(url);
var result = captured ? captured[1] : 'myDefaultValue';

【讨论】:

    猜你喜欢
    • 2019-01-12
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 2014-12-05
    • 2020-05-03
    • 2020-09-05
    • 2021-03-12
    相关资源
    最近更新 更多