2016-08-13 131 views
-3

爲了在動作之後更改圖片的z-index,我在js中編寫了以下代碼。「js Uncaught TypeError:無法設置未定義的屬性'zIndex'

$("id").click(function{ 

    document.getElementsByClassName.style.zIndex = 2; 
}); 

但是,它表明類似

js Uncaught TypeError: Cannot set property 'zIndex' of undefined

誤差有任何人面臨同樣的問題又解決了嗎? THX

+0

提及**類名**然後迭代應用。例如: - document.getElementsByClassName(「some_class」);'給出元素數組 – Abhi

+0

'.getElementsByClassName'方法沒有'style'屬性。 – melpomene

+0

是的,我忘了打印它。 – shinyMao

回答

0

第一getElementsByClassName需要傳遞給它的參數,以指定要接收的元素應該包含的類名。

只需選擇返回數組的第一個和該值進行操作時,一定要檢查返回數組包含任何元素:

$("id").click(function{ 
var elements = document.getElementsByClassName('some-class-name'); 
if (elements.length > 0) { 
    elements[0].style.zIndex = 2; 
} 

}); 

但我真的建議你使用jQuery來確保跨瀏覽器兼容。

$("id").click(function{ 
var elements = $('.some-class-name'); 
if (elements.length > 0) { 
    elements.first().css({ 'z-index' : 2 }); 
} 

}); 

編輯: 因爲你說,你想改變一個圖像對象的zIndex的,我用的第一個()的jQuery和[0]香草JS只得到第一個元素進行操作。但是,在這種情況下,僅使用唯一的id屬性作爲標識符來查詢僅一個元素。

+0

你好,你能告訴我爲什麼使用jQuery可以確保交叉瀏覽器兼容性? THX – shinyMao

+0

查看[jQuery當前瀏覽器的桌面和移動支持](http://jquery.com/browser-support/)取自[This SO answer](http://stackoverflow.com/questions/6384707/is-使用-jQuery的一個擔保換跨瀏覽器兼容性#6384757) –

1

也可以用jQuery做

$(".class_name").css("z-index","2"); 
+0

您的答案可能是對的,但您使用的** jQuery **未在問題 – Abhi

+0

中標記但問題代碼本身包含** jQuery **,這就是爲什麼我回答 –

+0

添加了jQuery標記。請爲您的答案增加一點解釋。 – Abhi

1

這應該工作:

所有你需要的是提供一個類名和遍歷元素:

$("id").click(function{ 
    var elems = document.getElementsByClassName("some_class"); 

    for(var i = 0; i < elems.length; i++) { 
     elems[i].style.zIndex = 2; 
    } 
}); 
0

如果您使用的是getElementsByClassName,則您在函數中缺少參數,並且元素採用數組格式,因此您還需要指定元素位置[0],或者在循環中執行此操作。這是你的運行示例。

$("#test").click(function(){ 
 
document.getElementById("test").style.zIndex = 0; 
 
document.getElementsByClassName("testClass")[0].style.zIndex = 999; 
 
}); 
 

 
$(".testClass").click(function(){ 
 
document.getElementsByClassName("testClass")[0].style.zIndex = 0; 
 
document.getElementById("test").style.zIndex = 999; 
 
});
#test{ 
 
    position:absolute; 
 
    width:100%; 
 
    height:100%; 
 
    background-color:red; 
 
    z-index:999; 
 
    } 
 

 
.testClass{ 
 
    position:absolute; 
 
    width:100%; 
 
    height:100%; 
 
    background-color:green; 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="test"> Test 
 
    </div> 
 

 
<div class="testClass">Test Class</div>

0

據我,因爲我們知道的ID在Javascript中是獨一無二的特定的元素,但在類案件事實並非如此。類是可重用的。

對於使用的類是具體哪些類的發生將要使用。

下面是我的代碼,它可以幫助我解決我的問題。

funtion displayModal(){ 
    var play_button_overlay = document.getElementsByClassName("play_button")[0]; 
    play_button_overlay.style.zIndex="1"; 
    } 
相關問題