【问题标题】:Conditional Redirect by Day of the Week按星期几的条件重定向
【发布时间】:2020-06-15 14:50:31
【问题描述】:

我正在寻找一种基于星期几将一个页面重定向到另一个页面的方法。我只希望相关页面从美国东部标准时间周日上午 12:00 到美国东部标准时间周二下午 2:00 重定向。

这就是我所拥有的。当我测试它时,它没有重定向到新的 URL。

<script> 
const rules = [ 
{ day: 0, url: 'https://www.whitehorsewine.com/pages/our-kitchen-1' }, // Redirect for Sunday
{ day: 1, url: 'https://www.whitehorsewine.com/pages/our-kitchen-1' }, // Redirect for Monday
{ day: 2, from: 0, to: 11, url: 'https://www.whitehorsewine.com/pages/our-kitchen-1' }, // Redirect for Tuesday until 2pm 
]; 
function getRedirectUrl() { 
const now = new Date(); 
const today = now.getDay(); 
const hours = now.getHours(); 
const first = rules.find(item => 
(item.day === undefined || item.day === today) && 
((item.from === undefined || item.from >= hours) && (item.to === undefined || item.to < hours)) 
); 
return first.url; 
} 
function redirect() { 
window.location.href = getRedirectUrl(); 
} 

</script>

不确定是否重要,但我正在使用 Shopify 的主题编辑器。

【问题讨论】:

  • 它现在在做什么?这与您预期的结果有何不同?
  • 我周一访问了该页面,但它没有重定向到新的 URL。

标签: javascript redirect shopify


【解决方案1】:

你离得太近了!

您的比较运算符只是倒退。

因此,根据您的结构方式和显示的数据,不可能找到既小于0 又大于11 的时间。

那就换个方式

item.from &gt;= hoursitem.from &lt;= hours

item.to === undefined || item.to &lt; hoursitem.to === undefined || item.to &gt; hours

我还会在您的返回和重定向逻辑中添加一些保护语句。还要确保您在某处致电redirect()。我在您的示例中没有看到它,这也是它不运行的另一个原因。

const rules = [ 
  { day: 0, url: 'https://www.whitehorsewine.com/pages/our-kitchen-1' }, // Redirect for Sunday
  { day: 1, url: 'https://www.whitehorsewine.com/pages/our-kitchen-1' }, // Redirect for Monday
  { day: 2, from: 0, to: 11, url: 'https://www.whitehorsewine.com/pages/our-kitchen-1' }, // Redirect for Tuesday until 2pm 
]; 

function getRedirectUrl() { 
  const now = new Date(); 
  const today = now.getDay(); 
  const hours = now.getHours(); 
  const first = rules.find(item => 
    (item.day === undefined || item.day === today) && 
    ((item.from === undefined || item.from <= hours) && (item.to === undefined || item.to > hours)) 
); 
  if (first === undefined) { return undefined } // Guard to return undefined instead of erroring out if it can't find a matching rule
  return first.url; 
} 

function redirect() { 
  let url = getRedirectUrl()
  // Guard to catch the undefined and not call the redirect on an undefined resource.
  if ( url !== undefined ) { window.location.href = url }
} 

redirect() // Added the call to redirect so the code actually gets run.

【讨论】:

  • 谢谢!这是我第一次尝试将脚本修补在一起,而不仅仅是对现有的进行小幅编辑,所以我处于未知领域。非常感谢令人鼓舞的回应!
猜你喜欢
  • 2015-05-13
  • 2022-08-10
  • 1970-01-01
  • 2017-01-12
  • 1970-01-01
  • 1970-01-01
  • 2021-06-29
  • 1970-01-01
  • 2014-06-26
相关资源
最近更新 更多