window.location.href跳转后,如何自动聚焦id为productCode的文本输入框?
Fixing Auto-Focus for
productCode Input on Page Reload with GET Params Hey there, I’ve run into this exact issue before—let’s break down why your jQuery .focus() isn’t working and get it sorted out.
Common Reasons It’s Failing
- DOM isn’t fully loaded yet: If you’re calling
.focus()before theproductCodeinput exists in the DOM, it’ll do nothing. - GET parameter detection is off: Maybe your logic to check for URL params isn’t correctly identifying when they’re present.
- Browser auto-focus interference: Some browsers auto-focus the first input on page load, which might override your code (though less likely here).
Working Solutions
Option 1: jQuery with DOM Ready + Reliable Param Check
Wrap your code in $(document).ready() to ensure the input exists, and use URLSearchParams (modern, reliable) to detect GET params:
$(document).ready(function() { // Parse URL parameters const urlParams = new URLSearchParams(window.location.search); // Check if any GET parameters exist (adjust if you need to target a specific param) if (urlParams.toString()) { const productCodeInput = $('#productCode'); // Make sure the input element exists before trying to focus if (productCodeInput.length > 0) { productCodeInput.focus(); // If it still doesn't work, try a tiny delay (rarely needed, but a fallback) // setTimeout(() => productCodeInput.focus(), 100); } } });
Option 2: Native JavaScript (No jQuery)
If you prefer ditching jQuery entirely, this native JS version works just as well:
document.addEventListener('DOMContentLoaded', function() { const urlParams = new URLSearchParams(window.location.search); if (urlParams.toString()) { const inputElement = document.getElementById('productCode'); if (inputElement) { inputElement.focus(); } } });
Extra Checks
- Ensure the
productCodeinput is visible (notdisplay: noneorvisibility: hidden)—you can’t focus a hidden element. - If your page loads content dynamically (e.g., via AJAX), run the focus code after the dynamic content is inserted into the DOM.
内容的提问来源于stack exchange,提问作者Alejandro Monzón
相关产品推荐
相关产品推荐

