是否可以使用 jquery 通过构造函数创建 DOM 元素?
我正在尝试对名为 h5p 的插件进行逆向工程,如果您向下滚动到“javascript”部分,您将看到以下步骤:
对象命名空间的声明(我假设不会污染全局命名空间
创建实际 DOM 元素的构造函数
构建 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})
.
关于javascript - 使用 jquery 构造 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37744336/