2013-10-17 36 views
0

我想改变一下就icon-埃夫里的时间用户的z-index点击图标指数-Z是+1,但我的代码无法正常工作:设置z-index的动态与JS

$(document).on('click', '.icon-layer-up', function() { 
     console.log($(this).parent(".ui-wrapper").css("z-index")); 
     var currentIndex = $(this).parent(".ui-wrapper").css("z-index"); 
     if (currentIndex = "auto") { 
     currentIndex = 0; 
     } 
     var num = currentIndex++; 
     $(this).parent(".ui-wrapper").css("z-index", num); 
    }); 

回答

1

您的问题是var num = currentIndex++;

currentIndex++将增加currentIndexcurrentIndex + 1,但它会返回原来的价值,所以num被分配到currentIndex原始值。只需使用var num = currentIndex + 1

如果您只想添加1,那么使用++并不是很好的编码习惯。如果您只是添加,请使用+ 1

+3

'VAR NUM = ++ CURRENTINDEX; .'增量+分配值 –

2

if(currentIndex = "auto") { 

if(currentIndex == "auto") { 

第一个很大的区别进行,你不打算转让,总是返回“自动”作为结果始终if语句运行,将currentIndex重置为0.

404也是正确的,你不想在这种情况下给我们“num ++”出于两个原因

  1. 它试图只分配,这将使你反正不正确的值之后,增加值,但是...
  2. 你的情况“民”,实际上是因为它是如何获得一个 。你需要将它转换为数字做加法:parseInt(num) + 1
1

,我与你的代码,这可能会或可能不会是一个问题,就是你缺少的数据参数注意到的第一件事你jQuery on事件。您还打算将您的活动应用到document.body而不是document

$(document.body/*changed*/).on('click', '.icon-layer-up', {}/*added*/, function() { 

接下来,你总是设置currentIndexauto再到0,而不是检查,看它是否等于auto

if (currentIndex ==/*fixed*/ "auto") { 

此外,您在最初设定currentIndex作为一个字符串,它会试图增加它当字符串只转换为数字,你的方式。您必须先尝试将其转换为Number,然后检查以确保它是Number,然后然后对其进行增量。

这么干脆固定的代码应该是:

$(document.body).on('click', '.icon-layer-up', {}, function() { 
     console.log($(this).parent(".ui-wrapper").css("z-index")); 
     var currentIndex = Number($(this).parent(".ui-wrapper").css("z-index")); 
     if (isNaN(currentIndex)) { // if is not a number, set it to 0 
     currentIndex = 0; 
     } 
     var num = currentIndex++; 
     $(this).parent(".ui-wrapper").css("z-index", num); 
    }); 

接下来,确保你阅读z-index,并了解它是如何工作的。 z-index将不会应用于static的默认position的元素。尝试将您的元素设置为position: relative;,您尝试应用z-index

参考z-index
Understanding CSS z-index
Adding z-index

在这种情况下使用