如何在javascript中创建一个元素并将参数传递给它? [英] How to create an element in javascript and pass parameters to it?
本文介绍了如何在javascript中创建一个元素并将参数传递给它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在新的 v1 web components 规范中,你可以通过 like 来创建一个新元素
In the new v1 web components spec, you can create a new element by saying like
class gg extends HTMLElement {
constructor(a) {
super();
}
}
customElements.define('gg-gg', gg);
然后你可以创建一个它的新实例,就像
and then you can create a new instance of it, by doing like
<gg-gg></gg-gg>
或
new gg(1);
甚至
document.createElement("gg-gg");
但在最后一种方式document.createElement("gg-gg")
中,您将如何为构造函数中的a
传递一个参数?>
But in that last way document.createElement("gg-gg")
, how would you pass a parameter into it for the a
in the constructor?
推荐答案
您可以使用一个函数来创建一个 class
表达式,其中默认参数用于设置 constructor
You can use a function to create a class
expression where default parameters are used to set constructor
const gcreate = (...props) => {
const gg = class extends HTMLElement {
constructor(a = props) {
console.log(a);
a.find(prop =>
typeof prop === "object"
&& !Array.isArray(prop))
["def"](789)
super();
}
}
customElements.define('gg-gg', gg);
return document.createElement("gg-gg");
}
let g = gcreate(
// pass parameters
"abc"
, 123
, [4,5,6]
, {def:(prop) => console.log(prop)}
, null, void 0
);
这篇关于如何在javascript中创建一个元素并将参数传递给它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文