2016-06-10 63 views
0

是否有可能创建一个使用jquery的构造函数的DOM元素?与jQuery的DOM元素的构造函数

我试图在所谓的h5p逆向工程插件,如果你向下滚动到“JavaScript的”部分中,您将看到以下步骤:

  1. 命名空间为对象的声明(我认为,以不污染全局命名空间

  2. 创建实际的DOM元素打造的DOM元素

  3. 次要的辅助功​​能的consrtuctor功能

我知道这个特定的代码是依赖于一个框架,但它有可能被复制到一个单独的js文件中吗?

var H5P = H5P || {}; 

H5P.GreetingCard = (function ($) { 
    /** 
    * Constructor function. 
    */ 
    function C(options, id) { 
    // Extend defaults with provided options 
    this.options = $.extend(true, {}, { 
     greeting: 'Hello world!', 
     image: null 
    }, options); 
    // Keep provided id. 
    this.id = id; 
    }; 

    /** 
    * Attach function called by H5P framework to insert H5P content into 
    * page 
    * 
    * @param {jQuery} $container 
    */ 
    C.prototype.attach = function ($container) { 
    // Set class on container to identify it as a greeting card 
    // container. Allows for styling later. 
    $container.addClass("h5p-greetingcard"); 
    // Add image if provided. 
    if (this.options.image && this.options.image.path) { 
     $container.append('<img class="greeting-image" src="' + H5P.getPath(this.options.image.path, this.id) + '">'); 
    } 
    // Add greeting text. 
    $container.append('<div class="greeting-text">' + this.options.greeting + '</div>'); 
    }; 

    return C; 
})(H5P.jQuery); 

这是我想象(警告:粗糙的伪领先):

// quick and dirty h5p prototyping 
<!DOCTYPE html> 
<html> 
<head> 
    <script>import jquery here<script> 
    $(document).ready(function(){ 

    // constructor for dom element 

    // secondary helpers for dom element 

    // initialize the element and append it to dom 


    }); 
    </script> 

</head> 
<body> 
    <h2> h5p prototyping</h2> 
</body> 

回答

1

如果我理解正确的话比你可以用这种方式使用jQuery创建DOM元素:

$(document).ready(function() { 
 
    var newDOM = $('<div/>', { 
 
    class: 'new-dom', 
 
    html: $('<span/>', { 
 
     text: 'NEW DOM!!' 
 
    }), 
 
    onClick: 'alert("Works EVEN JS");' 
 
    }); 
 

 
    $('body').append(newDOM); 
 
});
.new-dom { 
 
    color: red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


只需将DOM元素的必需属性添加到构造函数对象$('<nodeName/>', {settingsObject})的第二个参数即可。