-1

我需要在网页的每个链接中绑定onclick函数,所以我使用了这个函数

var links = document.getElementsByTagName('a');// total 5 links
for(var key in links){
   //always be true in IE, But just be true from second latest in chrome
   alert(isNaN(parseInt(key)));
   if(isNaN(parseInt(key))){
      break;
   }else{
      ...
   }
}

请帮忙,谢谢

更新:似乎是for(var key in links)的问题,当在IE中时,键成为链接的Id,但它只是chrome中的数字

4

2 回答 2

2

您正在枚举锚标签之外的其他内容,其中一些内容应该是NaN. 使用常规for循环:

for(var i=0; i<links.length; i++) {
    // do something with links[i], 
    // which is guaranteed to be
    // an anchor tag
}
于 2012-06-29T02:46:16.503 回答
1

如果您正在使用 jQuery(我强烈建议您这样做),请使用该$.isNumeric()函数。

您还应该document.getElementsByTagName用这样的 jQuery 选择器替换

$('a').each(function(index, tag) {
    if($.isNumeric($(tag.attr('SOMEATTRIBUTE'))) {
        // do whatever you want here
    } else {
        // do the other condition here
    }
});
于 2012-06-29T02:46:18.263 回答