通过data属性调用对象键,实现Summernote配置是否有更优方式?
eval() for Summernote Config Lookup Great question! Using eval() here is a risky choice—it opens up potential security vulnerabilities (if the data-editor value is ever tampered with to include malicious code) and is generally considered a bad practice in JavaScript. Let’s replace it with a cleaner, safer, and more maintainable approach.
The Core Fix: Object Bracket Notation
Instead of evaluating a string to access your config object, use JavaScript's bracket notation for object property access. Since your data-editor attribute holds a string that matches a key in summernote_config, this is the perfect use case.
Here’s the optimized code:
HTML (no changes needed)
<textarea name="footer_content" id="footer_content" class="form-control" data-editor="simple"></textarea>
JavaScript/jQuery
var summernote_config = { 'simple': { height: 100 }, 'full': { height: 200, styleTags: ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'] } }; $('[data-editor]').each(function () { // Cache the jQuery element to avoid repeated $(this) calls var $textarea = $(this); // Get the editor type from the data attribute var editorType = $textarea.data('editor'); // Safely retrieve the config using bracket notation var config = summernote_config[editorType]; // Optional: Handle cases where the config doesn't exist (prevent errors) if (config) { $textarea.summernote(config); } else { console.warn(`No Summernote configuration found for editor type: ${editorType}`); // Fallback to a default config if needed $textarea.summernote({ height: 150 }); } });
Why This Is Better
- Security: No risk of executing arbitrary code. Even if
data-editorcontains a malicious string, it will only attempt to access an object property (which will just returnundefinedinstead of running code). - Readability: Direct property access is far more intuitive than
eval()—other developers can immediately understand what’s happening. - Maintainability: Adding new editor configurations only requires adding a new key-value pair to
summernote_config—no changes to the lookup logic are needed. - Error Resilience: The optional check for
configprevents your code from throwing errors if an invaliddata-editorvalue is used, and lets you provide a sensible fallback.
Bonus: Alternative Attribute Access
If you prefer to get the raw string value directly (instead of relying on jQuery’s data() which auto-converts some types), you can use attr() instead:
var editorType = $textarea.attr('data-editor');
This works exactly the same for your use case.
内容的提问来源于stack exchange,提问作者kjdion84

