js未捕获类型错误:Cannot set property 'zIndex'undefined"
"js Uncaught TypeError: Cannot set property 'zIndex' of undefined"
为了在一个动作后改变图片的z-index,我在js中编写了以下代码:
$("id").click(function{
document.getElementsByClassName.style.zIndex = 2;
});
但是,它显示的错误像
有没有人遇到过同样的问题,并且已经解决了?THXjs Uncaught TypeError: Cannot set property 'zIndex' of undefined
第一个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中的first()和香草JS中的[0]来对第一个元素进行操作,只有。但是在这种情况下,只使用唯一的id属性作为标识符来查询一个元素。
也可以使用jquery
$(".class_name").css("z-index","2");
应该可以:
您所需要的只是提供一个类名并遍历元素:
$("id").click(function{
var elems = document.getElementsByClassName("some_class");
for(var i = 0; i < elems.length; i++) {
elems[i].style.zIndex = 2;
}
});
您需要为getElementsByClassName
提供参数。
如果您使用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>
据我所知,Javascript中的ID对特定元素是唯一的,但在类的情况下则不是。类是可重用的。
要使用class,必须指明你要使用的是哪一个类。
下面是我的代码,帮助我解决我的问题。
funtion displayModal(){
var play_button_overlay = document.getElementsByClassName("play_button")[0];
play_button_overlay.style.zIndex="1";
}
相关文章:
- $(this).prop('property') vs. this.property
- 为什么JavaScript可以'找不到给定的InnerHTML并返回Cannot set property
- Highcharts 3d调整zindex错误
- Jquery Dynamic property
- 在循环遍历对象 HTMLDivElement 时,应用 ChileNode 样式 zindex 在 firefox 和
- 为什么“如果( !Object.property)“,如果 Object 未定义,则中断
- 我怎样才能让JSLint停止抱怨Ember.js“.property()”
- ngRepeat filter by array-property
- JasmineJS 'isNot' property
- 未捕获的类型错误:无法读取属性'zIndex'Ionic(AngularJS)中未定义的
- 如何在Javascript/AngularJS中动态地将foo设置为Object Property Name
- 为什么这个函数在JS中返回undefined.property
- 如何在JavaScript函数中使用s:property
- Jquery Javascript Property Undefined
- OpenLayers 3 point text zIndex
- Javascript Object Property Undefined (GM_getValue(), GM_list
- 如何从 Javascript 设置 .net Public Property 值
- JQuery .sort() JavaScript Object by property value不起作用
- 用按钮和jquery切换“data-property”
- js未捕获类型错误:Cannot set property 'zIndex'undefined"