在JavaScript中测试DOM元素的类型 [英] Testing the type of a DOM element in JavaScript

查看:27
本文介绍了在JavaScript中测试DOM元素的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以测试JavaScript中元素的类型?

Is there a way to test the type of an element in JavaScript?

答案可能需要也可能不需要原型库,但是以下设置确实使用了该库.

The answer may or may not require the prototype library, however the following setup does make use of the library.

function(event) {
  var element = event.element();
  // if the element is an anchor
  ...
  // if the element is a td
  ...
}

推荐答案

您可以使用 typeof(N)来获取实际的对象类型,但是您要做的是检查标记,而不是DOM元素的类型.

You can use typeof(N) to get the actual object type, but what you want to do is check the tag, not the type of the DOM element.

在这种情况下,请使用 elem.tagName elem.nodeName 属性.

In that case, use the elem.tagName or elem.nodeName property.

如果您想真正发挥创意,可以使用标记名字典和匿名闭包代替,如果使用switch或if/else.

if you want to get really creative, you can use a dictionary of tagnames and anonymous closures instead if a switch or if/else.

这篇关于在JavaScript中测试DOM元素的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆