javascript - 按钮元素可以有子节点吗?
问题描述
如果我有一个<b>
内部<button>
标签,那么是标签<b>
的 childNode<button>
吗?考虑下面的代码:
<button id='mooo'><b>Cows can't mooo</b></button>
Javascript:
x = document.getElementById('mooo');
x.addEventListener("Click", mooo);
function mooo(e){
if(e.target.childNode == "B"){
console.log("B is a child of Button");
}else{
console.log("B is not a child of Button");
}
代码返回后者,但我只需要确定 B 是否确实不是 BUTTON 的孩子
解决方案
是的,button
元素是有内容的元素。您只是没有正确检查他们的内容;元素没有childNode
属性。有childNodes
(一个集合)、firstChild
、lastChild
和它们的元素版本children
、firstElementChild
、 和lastElementChild
,但没有childNode
。
您还使用Click
了而不是click
(事件名称区分大小写),e.target
它可能是b
元素而不是button
(您希望this
或e.currentTarget
知道您正在引用button
)。
现场示例:
var x = document.getElementById('mooo');
x.addEventListener("click", mooo);
function mooo() {
if (this.firstElementChild.tagName == "B") {
console.log("B is a child of Button");
} else {
console.log("B is not a child of Button");
}
console.log("Contents of the button:");
for (let child = this.firstChild; child; child = child.nextSibling) {
switch (child.nodeType) {
case 1: // Element
console.log(child.tagName + " element, innerHTML = " + child.innerHTML);
break;
case 3: // Text node
console.log("Text node, nodeValue = " + child.nodeValue);
break;
default:
console.log(child.nodeName);
break;
}
}
}
<button id='mooo'><b>Cows can't mooo</b></button>
相反,input type="button"
元素是无效元素;他们没有内容,他们的childNodes
收藏总是空的。
推荐阅读
- css - 生产中的材质 UI 类名称无法正确解析
- python - 如何检查 Python Multiprocessing 中的 Process 类是否有效?
- php - 如何获取数组元素的出现次数并使用 PHP 中的 Python 字典等计数器保存元素?
- listview - 访问 xamarin.android 中列表视图行内的文本视图
- android - 键盘的Android Webview Focus问题
- c# - Dynamics NAV 仓库拣货可以通过 Web 服务更新吗?
- kubernetes - Kubernetes 在编码后将 env 变量设置为来自 configMap 的值
- android - 类似于#if #endif for AndroidManifest.xml
- crystal-reports - Crystal 中子报表(链接和非链接)和主报表的执行顺序
- r - R函数检查字符串中的多个文本