基于jQuery迭代创建变更函数,实现表单偏好设置
Implementing Form Preference Settings with Your Object Array
Let’s break down how to turn your preferences array into a working feature. Each entry in your array defines a trigger condition (when a base field matches a specific value) and an action (modify a target field). Here’s a step-by-step implementation using jQuery:
Step 1: Core Logic Overview
We’ll:
- Listen for changes on all base fields referenced in your preferences
- When a base field changes, find all matching preferences
- Execute the specified action (like updating the target field’s content)
Step 2: Full Working Code
Here’s the complete implementation, with comments explaining each part:
var preferences = [ { base_field:"field1", base_value:"1", preference_type:"change", target_field:"field2_div legend", target_value:"New Field 2 Legend" }, { base_field:"field1", base_value:"2", preference_type:"change", target_field:"field2_div legend", target_value:"New Field 2 Legend" } ]; // Initialize preferences when the page loads $(document).ready(function() { // Collect unique base fields to avoid duplicate event listeners const uniqueBaseFields = [...new Set(preferences.map(pref => pref.base_field))]; // Attach change listeners to each base field uniqueBaseFields.forEach(fieldId => { $(`#${fieldId}`).on('change input', function() { applyMatchingPreferences($(this).attr('id'), $(this).val()); }); }); // Apply initial preferences based on default field values uniqueBaseFields.forEach(fieldId => { applyMatchingPreferences(fieldId, $(`#${fieldId}`).val()); }); }); // Find and apply all preferences matching the current base field state function applyMatchingPreferences(baseFieldId, currentValue) { const matchingPrefs = preferences.filter(pref => pref.base_field === baseFieldId && pref.base_value === currentValue ); matchingPrefs.forEach(pref => { switch(pref.preference_type) { case 'change': updateTargetField(pref); break; // Add support for other types later (e.g., "show", "hide") default: console.warn(`Unsupported preference type: ${pref.preference_type}`); } }); } // Handle the "change" action for target fields function updateTargetField(preference) { const $target = $(preference.target_field); // Warn if target field doesn't exist (helps with debugging) if (!$target.length) { console.warn(`Target element not found: ${preference.target_field}`); return; } // Update form controls (input/select/textarea) or static elements (legend/div) if ($target.is('input, select, textarea')) { $target.val(preference.target_value); $target.trigger('change'); // Trigger change event for dependent scripts } else { $target.text(preference.target_value); } }
Key Features Explained
- Dynamic Listener Setup: We automatically collect unique base fields so you don’t have to manually add listeners for every new preference.
- Initial State Application: Preferences are applied on page load to match the default values of your form fields.
- Extensible Structure: The
switchstatement inapplyMatchingPreferencesmakes it easy to add new preference types (like "show" or "hide") later. - Error Handling: Warnings for missing target fields help you debug issues quickly.
Content of the question originates from Stack Exchange, asked by Sam Craven
相关产品推荐
相关产品推荐

