Featherlight灯箱关闭后如何获取输入文本框的值?
Hey there! I totally get why this is frustrating—you close the Featherlight modal, try to grab the input value via afterClose, and all you get is undefined. Let's break down why this happens and how to fix it.
Why You're Getting Undefined
By default, Featherlight removes the modal's content from the DOM as soon as it closes. That means when the afterClose trigger fires, your input element doesn't exist anymore. Trying to access its value at that point will naturally return undefined.
Solutions to Grab the Value
Here are a few reliable ways to get that input value after closing the modal:
1. Save the Value Before Closing (Most Common Approach)
Use the beforeClose hook instead—this runs right before the modal is removed from the DOM, so your input element is still there. Store the value in a variable, then use it in afterClose:
let userInput; // Initialize Featherlight with your form $.featherlight('#your-form-container', { beforeClose: function() { // Grab the value while the input is still in the DOM userInput = $(this.$content).find('input[type="text"]').val(); }, afterClose: function() { // Now you can use the saved value! console.log('Input value:', userInput); } });
2. Keep the Modal Content in the DOM (Persist Option)
If you need to reuse the form later or want to access elements post-close, enable the persist: true option. This keeps the content in the DOM after closing, but remember to clean it up if you don't need it anymore to avoid clutter:
$.featherlight('#your-form-container', { persist: true, afterClose: function() { const inputValue = $(this.$content).find('input[type="text"]').val(); console.log('Input value:', inputValue); // Optional: Manually remove the content if you don't need it again this.$content.remove(); } });
3. Track the Value in Real-Time
If you need to monitor the input as the user types, bind an input event to the field and save the value to a variable immediately. This way, you'll always have the latest value ready when afterClose runs:
let liveInputValue = ''; // Target your input field (adjust the selector to match your element) $('#your-input-id').on('input', function() { liveInputValue = $(this).val(); }); $.featherlight('#your-form-container', { afterClose: function() { console.log('Latest input value:', liveInputValue); } });
Pick the method that fits your use case best—most of the time, the first approach is the cleanest and works for standard form scenarios.
内容的提问来源于stack exchange,提问作者Kosem

