我正在开发一个构造函数,我可以按照以下代码中显示的代码注释中的说明使用它:
//CONSTRUCTOR
//creates a child element of the specified kind
//adds the child to specified parent
//optionally assigns the child an ID
// optionally assigns the child up to 4 classes
function Adjoin(childKind = undefined, childID = undefined, firstChildClass = undefined, secondChildClass = undefined, thirdChildClass = undefined, fourthChildClass = undefined) {
if (!(this instanceof Adjoin)) {
return new Adjoin(childKind = undefined, childID = undefined, firstChildClass = undefined, secondChildClass = undefined, thirdChildClass = undefined, fourthChildClass = undefined);
}
this.childKind = childKind;
this.childID = childID;
this.firstChildClass = firstChildClass;
this.secondChildClass = secondChildClass;
this.thirdChildClass = thirdChildClass;
this.addChildTo = function(parentID) {
const parent = document.getElementById(parentID);
const child = document.createElement(childKind);
parent.appendChild(child);
if (childID !== undefined) {
child.setAttribute("id", childID);
}
if (firstChildClass !== undefined) {
child.classList.add(firstChildClass);
}
if (secondChildClass !== undefined) {
child.classList.add(secondChildClass);
}
if (thirdChildClass !== undefined) {
child.classList.add(thirdChildClass);
}
if (fourthChildClass !== undefined) {
child.classList.add(fourthChildClass);
}
}
};
如果我在某处输入这样的代码,这将起作用:
new Adjoin("div", "foo_id", "foo_class").addChildTo("some_parent")
这也可以正常工作:
new Adjoin("div").addChildTo("some_parent")
我坚持的是检查第一个参数是否是 HTML 标记名称之一的方法。例如,如果代码输入为:
new Adjoin("not_an_html_element", "foo_id", "foo_class").addChildTo("manchoo_parent")
提前致谢!
更新
好吧,看来我发布这个问题有点太快了!我输入了以下代码:
new Adjoin(75).addChildTo("footer");
并得到这个错误:
未捕获的 DOMException:无法在“文档”上执行“createElement”:提供的标记名称(“75”)不是有效名称。
所以已经有一个内置的错误。
但是,当我输入以下代码时:
new Adjoin("DaveyJones").addChildTo("footer");
我在我的网站的页脚中添加了以下“标签”:
<daveyjones></daveyjones>
显然,这不是一个有效的 HTML 标记。
任何不是字符串的内容都会引发错误,但任何字符串都将被添加到 HTML 标记中而不会出现错误。
另一个更新
我按照 user2676208 的建议尝试了这个,并在这个问题中将其设置为条件:
if (document.createElement(this.childKind).toString() != "[HTMLUnknownElement]") {
console.log("That is a valid HTML element!")
} else {
console.log("That is NOT a valid HTML element!")
}
但是,它总是记录“这是一个有效的 HTML 元素!” 无论我使用“div”、“DaveyJones”还是“anyOtherString”。
尽管我不喜欢这个想法,但我可能不得不通过设置标签名称数组并在循环中进行比较来做到这一点。我只是真的希望有一种方法可以避免这种情况,因为这对我来说似乎是笨拙的。我希望 Javascript 已经有一种检查有效 HTML 的方法......