首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >检查作为函数参数输入的字符串是否为HTML标记名之一

检查作为函数参数输入的字符串是否为HTML标记名之一
EN

Stack Overflow用户
提问于 2018-06-17 00:52:38
回答 3查看 44关注 0票数 1

我正在开发一个构造器,我可以使用下面代码中所示的代码注释:

代码语言:javascript
复制
//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的建议,并在this question中将其设置为条件:

代码语言:javascript
复制
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的方法……

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50889865

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档