javascript InnerHTML 获取 Div 名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6560232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 21:06:21  来源:igfitidea点击:

InnerHTML getting Div Name

javascripthtmlundefinedinnerhtml

提问by Howdy_McGee

I am trying to get a name of a DIV

我正在尝试获取 DIV 的名称

<div id="test" name="info1" onclick="func(this.name)">This is div 1</div>

but when I try to print out the name of the div using innerHTML is comes back as undefined. Can this be done or am i doing something wrong?

但是当我尝试使用 innerHTML 打印出 div 的名称时,返回未定义。这可以完成还是我做错了什么?

回答by Tak

According to W3Schoolsa divcannot have a nameattribute, but it can have an id, classor title. I think the DOM isn't recognising the attribute, therefore not making it available to Javascript.

根据W3Schools,adiv不能有name属性,但可以有id,classtitle。我认为 DOM 无法识别该属性,因此无法将其提供给 Javascript。

I made an example herewhich shows titleworking and namefailing as you describe.

我在这里做了一个例子,它显示了你描述的title工作和name失败。

回答by Carl

Best way to grab an attribute off a node is to use getAttribute as only a small subset of attributes are accessible directly (Title for instance can be, where as alt can't).

从节点中获取属性的最佳方法是使用 getAttribute,因为只有一小部分属性可以直接访问(例如,Title 可以,而 alt 则不能)。

The getAttribute() method will also work fine with none standard attributes (which can be pretty useful at times)

getAttribute() 方法也可以在没有标准属性的情况下正常工作(有时非常有用)

The below code should pass it the nodes name to the func function correctly :)

下面的代码应该正确地将节点名称传递给 func 函数:)

<div id="test" name="info1" onclick="func(this.getAttribute('name')">This is div 1</div>

Hope that helps.

希望有帮助。

回答by nicosantangelo

If you want to get the name of the div, you should write some code that can get the attribute from an element (if you're not interested in cross-browser support just use elem.getAttribute)

如果您想获取 div 的名称,您应该编写一些可以从元素中获取属性的代码(如果您对跨浏览器支持不感兴趣,只需使用 elem.getAttribute)

For example:

例如:

    var getAttr = function(ele, attr) {
        var result = ele.getAttribute(attr) || ele[attr] || null, attrs, len;
        if( !result ) {
            attrs = ele.attributes;
            len = attrs.length;
            for(var i = 0; i < len; i++)
               if(attrs[i].nodeName === attr)
                  result = attrs[i].nodeValue;
        }
        return result;
};

Then you could do

那么你可以做

<div id="test" name="info1" onclick="func(getAttr(this, 'name'))">This is div 1</div>