1

我正在尝试查找页面内的任何标签是否包含 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 的标签中查找所有属性:(例如在 <a href="javascript:void(0)"> 中)知道如何将其添加到函数的逻辑中吗?

谢谢!

4

3 回答 3

1

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

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:']");

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

于 2011-11-09T20:17:00.303 回答
0

改变:

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

至:

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

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

于 2011-11-09T20:06:57.180 回答
0

我会这样做:

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/

于 2011-11-09T20:45:45.263 回答