移动端加载时用jQuery修改按钮文本失效问题求助
First, let's break down why your original code isn't working as expected:
- You're checking the window width before the document is fully loaded, which means the
.mehranzeigenelements might not exist yet when the check runs. - The code only runs once when the script loads—if a user resizes their browser from desktop to mobile (or vice versa), the text won't update dynamically.
Here's the corrected approach that addresses both issues:
$(document).ready(function() { // Create a reusable function to update the button text function updateMehranzeigenText() { const windowWidth = $(window).width(); const $mehranzeigen = $('.mehranzeigen'); // Check if we're on mobile (<768px) if (windowWidth < 768) { // Only change the text if it matches the original (trim whitespace to avoid mismatches) if ($mehranzeigen.text().trim() === 'Hier klicken für mehr Informationen') { $mehranzeigen.text('Mehr Informationen'); } } else { // Optional: Revert back to original text when on desktop if ($mehranzeigen.text().trim() === 'Mehr Informationen') { $mehranzeigen.text('Hier klicken für mehr Informationen'); } } } // Run the function on page load updateMehranzeigenText(); // Run the function whenever the window is resized (with debounce to avoid excessive calls) $(window).on('resize', function() { clearTimeout(window.resizeTimeout); window.resizeTimeout = setTimeout(updateMehranzeigenText, 100); }); });
Key Improvements:
- Document Ready Wrapper: Ensures we only manipulate elements after they've been fully loaded into the DOM.
- Reusable Function: Makes it easy to call the text update logic both on page load and during window resizing.
- Debounced Resize Event: Prevents the function from running hundreds of times as the user drags the window edge (the 100ms delay is adjustable).
- Trimmed Text Check: Uses
.trim()to account for any accidental whitespace in the button text, which might have been causing your original check to fail silently. - Optional Desktop Revert: Adds logic to switch back to the original text when the screen is larger than 768px (you can remove this block if you don't need this behavior).
Troubleshooting Tips if It Still Doesn't Work:
- Verify jQuery is loaded before this script (check the browser console for
$ is not definederrors). - Confirm the
.mehranzeigenselector targets the right elements (addconsole.log($mehranzeigen)inside the function to see if elements are found). - Check if other scripts are modifying the button text after this one runs—adjust the execution order if needed.
内容的提问来源于stack exchange,提问作者Max
相关产品推荐
相关产品推荐

