【发布时间】: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