Mac环境下特定页面首次加载日期预填充失效问题求助
Let's break down your issue and work through a solution step by step:
The Core Issues
You’re hitting that "cannot assign to null" error specifically on first Mac visits (or after clearing cache) because of two key problems:
- Broken URL check logic: Your
indexOfcondition is backwards. When the URL doesn’t contain/ccpaRequest.html,indexOfreturns-1—but JavaScript treats-1as a "truthy" value, so your code runs on every page. On non-target pages,#DateFielddoesn’t exist, triggering the error. - Potential race condition with merged JS: Even with
$(document).ready(), merged JS files might load out of order, or the DOM might not be fully parsed when your code executes on first load (Mac browsers can have stricter caching/rendering behavior here).
Fixes to Implement
1. Correct the URL Check
First, fix the condition to only run the code when we’re actually on the target page:
// Replace this flawed check: if($(location).attr('href').indexOf("/ccpaRequest.html")) // With this exact match check: if(window.location.href.indexOf("/ccpaRequest.html") !== -1)
This ensures your date-filling code only runs when it’s supposed to.
2. Use jQuery for Safer Element Handling
Instead of document.getElementById (which throws an error if the element is missing), use jQuery’s selector—it handles missing elements gracefully. Update the date assignment line:
// Replace this: document.getElementById('DateField').value = d; // With this: $('#DateField').val(d);
3. Strengthen DOM Readiness (Optional but Reliable)
For extra protection against race conditions, you can wait specifically for the #DateField element to exist before modifying it:
$(document).ready(function(){ if(window.location.href.indexOf("/ccpaRequest.html") !== -1) { // Wait for the target input to be fully loaded $('#DateField').ready(function() { const date = new Date(); const months = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"]; const formattedDate = `${date.getDate()}-${months[date.getMonth()]}-${date.getFullYear()}`; $(this).val(formattedDate); }); } });
Full Modified JavaScript Code
Here’s the complete, fixed version of your script:
$(document).ready(function(){ if(window.location.href.indexOf("/ccpaRequest.html") !== -1) { if($('div.ccpa-form-content').length){ var date = new Date(); const months = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"]; const monthName = months[date.getMonth()]; var d = date.getDate() + "-" + monthName + "-" + date.getFullYear(); $('#DateField').val(d); } } });
Additional Tips
- Load scripts at the bottom of your HTML: Place your merged JS files right before the closing
</body>tag to ensure the DOM is fully parsed before scripts run. - Verify JS merge order: Double-check that jQuery is loaded before your custom script in your merge configuration—if jQuery isn’t available when your code runs,
$(document).ready()won’t work as intended.
内容的提问来源于stack exchange,提问作者surya

