繁体   English   中英

带有jQuery的DOM元素的构造方法

[英]Constructor for a DOM element with jquery

是否可以使用jquery使用构造函数创建DOM元素?

我正在尝试对名为h5p的插件进行反向工程,如果您向下滚动到“ javascript”部分,则会看到以下步骤:

  1. 对象的名称空间声明(我假设不会污染全局名称空间

  2. 一个构造函数,可创建实际的DOM元素

  3. 建立DOM元素的辅助功能

我知道该特定代码依赖于框架,但是是否可以仅将其复制到单个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>

如果我理解正确,那么您可以通过以下方式使用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})第二个参数中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM