You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过data属性调用对象键,实现Summernote配置是否有更优方式?

Better Alternative to 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-editor contains a malicious string, it will only attempt to access an object property (which will just return undefined instead 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 config prevents your code from throwing errors if an invalid data-editor value 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:55:07