我正在尝试用两个不同的for loops检查两件事。如果一个元素具有attribute,则该方法有效!第二个循环应检查alt标记是否为空。我认为将第一个iterator值传递给第二个将分配第二个循环。但这不起作用!有人可以帮我解决这个问题吗?

function altChecker() {
    var doc = document,

        getStartedBtn = doc.getElementById('getStartedBtn');

        EventUtility.addHandler(getStartedBtn, 'click', function() {

        var all = doc.getElementsByTagName("IMG");

        console.log('success!');

        for (var i = 0, max = all.length; i < max; i++) {
            if (all[i].hasAttribute('alt')) {
                console.log('Yes, this has a ' + all[i].nodeName + ' tag!');
            } else {
                console.log('Sorry ' + all[i].nodeName + ' tag, doesn\'t have an alt tag!');
            }

        }
        for (var j = i, max2 = all; j < max2; j++) {
            if(! $(all[j]).attr('alt')){
                console.log('This is empty');
            } else {
                console.log('This aint');
            }
        };

    });
}

最佳答案

我认为不需要2个循环

function altChecker() {
    var doc = document,

    getStartedBtn = doc.getElementById('getStartedBtn');

    EventUtility.addHandler(getStartedBtn, 'click', function() {

        var all = doc.getElementsByTagName("IMG");

        console.log('success!');

        for (var i = 0; i < all.length; i++) {
            if (all[i].hasAttribute('alt')) {
              if (all[i].alt === '') {
                  console.log('this has a ' + all[i].nodeName + ' tag BUT it is empty!');
              } else {
                  console.log('Yes, this has a ' + all[i].nodeName + ' tag and it is NOT empty!');
              }
            } else {
                console.log('Sorry ' + all[i].nodeName + ' tag, doesn\'t have an alt tag!');
            }

        }
    });
}

10-04 22:38