我正在构建一个可以使用的构造函数,如以下代码所示的代码注释所述:
//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:无法在'Document'上执行'createElement':提供的标记名称('75')不是有效名称。
因此,已经存在一个内置错误。
但是,当我输入以下代码时:
new Adjoin("DaveyJones").addChildTo("footer");
我将以下“标签”添加到网站的页脚中:
<daveyjones></daveyjones>
显然,这不是有效的HTML标签。
对于不是字符串的任何东西都将引发错误,但是会将任何字符串添加到HTML标记中而不会出错。
还可以更新
我按照user2676208和this question的建议尝试了此操作,方法是将其设置为有条件的:
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 ...
最佳答案
我认为我不能将其标记为重复项,但是您应该在此处查看问题:Verify whether a string is a valid HTML tag name。
从斯特里纳那里的答案,
function isValid(input) {
return document.createElement(input).toString() != "[object HTMLUnknownElement]";
}
关于javascript - 检查作为函数参数输入的字符串是否为HTML标记名之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50889865/