[英]Javascript modulo operation in IE7
為了向List中的每個第三項添加一個類,我使用如下的模運算:
var projectElements = document.getElementById("projectList").children;
var iCount = 0;
for (var i in projectElements) {
iCount++;
if (iCount % 3 == 0) {
if (projectElements[i].className == "") {
projectElements[i].className += "projectLinkLast";
}
else {
projectElements[i].className += " projectLinkLast";
}
}
}
它在Firefox和其他瀏覽器中工作正常,除了Internet Explorer 7.有沒有人知道為什么?
嘗試使用.setAttribute("className", "blah")
而不是.className。
在JSFiddle上獲得了代碼的演示,似乎正在運行: http : //jsfiddle.net/LWsTn/6/
如果你要使用jQuery。 采用:
$("#projectList :nth-child(3n").addClass("projectLinkLast");
文檔: http : //api.jquery.com/nth-child-selector/
jQuery使用的addClass方法可能有所幫助
classNames = value.split(rspace);
for (i = 0, l = this.length; i < l; i++) {
elem = this[i];
if (elem.nodeType === 1) {
if (!elem.className && classNames.length === 1) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for (c = 0, cl = classNames.length; c < cl; c++) {
if (!~setClass.indexOf(" " + classNames[c] + " ")) {
setClass += classNames[c] + " ";
}
}
elem.className = jQuery.trim(setClass);
}
}
}
這不是模運算符的問題。 問題可能是你for...in
一個宿主對象中使用for...in
(在這種情況下,是一個元素的children
屬性),這是一個壞主意,並不能保證按預期工作(或者根本不工作)。 此外,並非所有瀏覽器都支持children
(盡管它在IE 7中,因此這不是該瀏覽器中的問題)。 我會建議以下內容:
var iCount = 0, child = document.getElementById("projectList").firstChild;
while (child) {
if (child.nodeType == 1) { // Only deal with elements
iCount++;
if (iCount % 3 == 0) {
if (child.className == "") {
child.className = "projectLinkLast";
}
else {
child.className += " projectLinkLast";
}
}
}
child = child.nextSibling;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.