测试 DOM 中所有元素节点的属性是否存在

发布于 2024-12-14 07:54:21 字数 972 浏览 2 评论 0原文

我试图查找页面内的任何标签是否包含 js 事件属性,例如 onload、onunload、onfocus 等,... 为此,我有一组事件要检查(我想我已经全部拥有了):

var attr = [
"onLoad",
"onunload",
"onclick",
"ondblclick",
"onmousedown",
"onmouseup",
"onmouseover",
"onmousemove",
"onmouseout",
"onfocus",
"onblur",
"onkeypress",
"onkeydown",
"onkeyup",
"onsubmit",
"onreset",
"onselect",
"onchange"]; 

然后我获取所有 elementsByTagName 并想要检查它们的属性:

var getAttrs = function() {
var i = 0,
    j,
    all = document.getElementsByTagName('*'),
    max = all.length,
    eventsLen = attr.length;


for (; i < max; i++) {

    console.log('iterating through objects');

    for (j = 0; j < eventsLen; j++) {

       if (all[i].hasAttribute(attr[j])) {
          console.log('found an instance of an intrinsec event', attr[j]);
       }

    }

}

};

这不起作用,我没有得到任何我想找到的属性。

此外,我想找到使用 javascript 的所有标签中的所有属性:(例如 中)知道如何将其添加到函数的逻辑中吗?

谢谢!

I'm trying to find if any of the tags inside a page contain a js event attribute, such as onload, onunload, onfocus etc, ...
To do so I have an array of events to check for (I think I have them all):

var attr = [
"onLoad",
"onunload",
"onclick",
"ondblclick",
"onmousedown",
"onmouseup",
"onmouseover",
"onmousemove",
"onmouseout",
"onfocus",
"onblur",
"onkeypress",
"onkeydown",
"onkeyup",
"onsubmit",
"onreset",
"onselect",
"onchange"]; 

and then I get all the elementsByTagName and want to check for their attribute:

var getAttrs = function() {
var i = 0,
    j,
    all = document.getElementsByTagName('*'),
    max = all.length,
    eventsLen = attr.length;


for (; i < max; i++) {

    console.log('iterating through objects');

    for (j = 0; j < eventsLen; j++) {

       if (all[i].hasAttribute(attr[j])) {
          console.log('found an instance of an intrinsec event', attr[j]);
       }

    }

}

};

This isn't working and I'm not getting any of the attributes I wanted to find.

Additionally, I'd like to find all attributes within all tags that use javascript: (such as in <a href="javascript:void(0)">) Any idea how I could add that to the function's logic?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

天荒地未老 2024-12-21 07:54:21

如果要获取具有任一属性的所有元素,可以使用以下代码:

var attr = ["onLoad", "onunload", "onclick", "ondblclick", "onmousedown",
            "onmouseup", "onmouseover", "onmousemove", "onmouseout", "onfocus",
            "onblur", "onkeypress", "onkeydown", "onkeyup", "onsubmit", "onreset",
            "onselect", "onchange", "href^='javascript:'"];
var selector = "[" + attr.join("],[") + "]";
//selector looks like "[onLoad][onunload]...[href^='javascript:']"
var eitherAttribute = document.querySelectorAll(selector);
for(var i=0, len=eitherAttribute.length; i<len; i++){
    console.log(eitherAttribute[i]); //Logs the element
}

如果要选择与多个属性匹配的所有元素,请使用:

//Example: onclick, AND href starting with javascript:
document.querySelectorAll("[onclick][href^='javascript:']");

有关详细信息,请参阅 MDN: document.querySelectorAll
如果您需要更灵活的选择器,请查看:MDN:选择器

If you want to get all elements which have either attribute, the following code can be used:

var attr = ["onLoad", "onunload", "onclick", "ondblclick", "onmousedown",
            "onmouseup", "onmouseover", "onmousemove", "onmouseout", "onfocus",
            "onblur", "onkeypress", "onkeydown", "onkeyup", "onsubmit", "onreset",
            "onselect", "onchange", "href^='javascript:'"];
var selector = "[" + attr.join("],[") + "]";
//selector looks like "[onLoad][onunload]...[href^='javascript:']"
var eitherAttribute = document.querySelectorAll(selector);
for(var i=0, len=eitherAttribute.length; i<len; i++){
    console.log(eitherAttribute[i]); //Logs the element
}

If you want to select all elements which match multiple attributes, use:

//Example: onclick, AND href starting with javascript:
document.querySelectorAll("[onclick][href^='javascript:']");

For more information, see MDN: document.querySelectorAll.
If you need more flexible selectors, have a look at: MDN: Selectors

各空 2024-12-21 07:54:21

更改:

if (all[i].hasAttribute(attr[j])) {

至:

if (all[i][attr[j]]) {

因为它也可以是属性,而不是属性。

Change:

if (all[i].hasAttribute(attr[j])) {

To:

if (all[i][attr[j]]) {

As it can also be a property and as opposed to an attribute.

薄荷港 2024-12-21 07:54:21

这就是我要做的:

var checkForEventAttrs = (function () {
    var eventAttrs = [ /* a list of attribute name strings */ ];

    function walkTheDOM( node, func ) {
          func( node );
          node = node.firstElementChild;
          while ( node ) {
              walkTheDOM( node, func );
              node = node.nextElementSibling;
          }
     }

    return function () {
        walkTheDOM( document.body, function ( node ) {
            eventAttrs.forEach( function ( eventAttr ) {
                if ( node.hasAttribute( eventAttr ) ) {
                    console.log( 'The attribute ' + eventAttr + ' found.' );
                }
            });
        });
    };
})();

然后调用该函数将这些属性记录到控制台中:

checkForEventAttrs();

现场演示: http://jsfiddle.net/F5AEy/

This is how I would do it:

var checkForEventAttrs = (function () {
    var eventAttrs = [ /* a list of attribute name strings */ ];

    function walkTheDOM( node, func ) {
          func( node );
          node = node.firstElementChild;
          while ( node ) {
              walkTheDOM( node, func );
              node = node.nextElementSibling;
          }
     }

    return function () {
        walkTheDOM( document.body, function ( node ) {
            eventAttrs.forEach( function ( eventAttr ) {
                if ( node.hasAttribute( eventAttr ) ) {
                    console.log( 'The attribute ' + eventAttr + ' found.' );
                }
            });
        });
    };
})();

and then just call that function to log those attribute into the console:

checkForEventAttrs();

Live demo: http://jsfiddle.net/F5AEy/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文