【问题标题】:Only execute script if URL parameter exists仅在 URL 参数存在时执行脚本
【发布时间】:2022-11-25 16:25:54
【问题描述】:

有没有办法让此脚本仅在 URL 中存在 utm_campaign 参数时执行?

function fillFormArea(){
  
  const select = document.getElementById('property.cust_AreaOfInterest.value'); 
  const queryString = window.location.search;
  const urlParams = new URLSearchParams(queryString);  //parse the query string
  const country = urlParams.get('utm_campaign');  // Store the parsed area of interest
  
   select.value = country;  // fill the form with the area of interest
}

if (document.readyState === 'loading') {  // Loading hasn't finished yet
  document.addEventListener('DOMContentLoaded', fillFormArea)
} 
else {  // `DOMContentLoaded` has already fired
  fillFormArea();
}

【问题讨论】:

  • if(country !== null) 检查参数是否已通过.. 顺便说一下,只需在 fillFormArea 中检查它作为第一个条件,并将事件侦听器附加到 DOMContentLoaded 事件,而无需对 document.readystate 进行复杂的检查。该字符串 property.cust_AreaOfInterest.value 上的 getElementById 非常不清楚
  • 脚本在加载时执行,您必须检查服务器端的查询参数,如果缺少参数,则不要在页面上包含脚本。或者检查函数中的参数,参数不存在不做任何处理直接返回。为什么要进行如此复杂的加载检测?脚本是在页面上动态添加的,还是脚本标记中存在async 属性?

标签: javascript


【解决方案1】:
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const country = urlParams.get('utm_campaign');
if ( country === null) {
//does not exist
}else{
const select = document.getElementById('property.cust_AreaOfInterest.value');
select.value = country
}

【讨论】:

    猜你喜欢
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2018-07-06
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    • 2015-03-15
    相关资源
    最近更新 更多