用jquery去获取元素 用原生js去写样式为什么 会报错
varcheckgread=document.getElementsByClassName('checkgread')[0];varcheckrank=document....
var checkgread = document.getElementsByClassName('checkgread')[0];
var checkrank = document.getElementsByClassName('checkrank')[0];
var checksoc = document.getElementsByClassName('checksoc')[0];
var greaderror = document.getElementsByClassName('greaderror')[0];
var ocheckgread = document.getElementById('checkgread');
var ocheckrank = document.getElementById('checkrank');
var ochecksoc = document.getElementById('checksoc');
var ogreaderror = document.getElementById('greaderror');
function display(div1,div2,div3,div4,div5){
div1.onclick = function(){
div2.style.display = "block";
div3.style.display = "none";
div4.style.display = "none";
div5.style.display = "none";
}
}
display(checkgread,ocheckgread,ocheckrank,ochecksoc,ogreaderror);
display(checkrank,ocheckrank,ocheckgread,ochecksoc,ogreaderror);
display(checksoc,ochecksoc,ocheckgread,ocheckrank,ogreaderror);
display(greaderror,ogreaderror,ocheckgread,ocheckrank,ochecksoc);
这样写没有问题 但是把获取元素写成var checkgread =$('.checkgread')[0];
这样就会报错 提示display未定义 展开
var checkrank = document.getElementsByClassName('checkrank')[0];
var checksoc = document.getElementsByClassName('checksoc')[0];
var greaderror = document.getElementsByClassName('greaderror')[0];
var ocheckgread = document.getElementById('checkgread');
var ocheckrank = document.getElementById('checkrank');
var ochecksoc = document.getElementById('checksoc');
var ogreaderror = document.getElementById('greaderror');
function display(div1,div2,div3,div4,div5){
div1.onclick = function(){
div2.style.display = "block";
div3.style.display = "none";
div4.style.display = "none";
div5.style.display = "none";
}
}
display(checkgread,ocheckgread,ocheckrank,ochecksoc,ogreaderror);
display(checkrank,ocheckrank,ocheckgread,ochecksoc,ogreaderror);
display(checksoc,ochecksoc,ocheckgread,ocheckrank,ogreaderror);
display(greaderror,ogreaderror,ocheckgread,ocheckrank,ochecksoc);
这样写没有问题 但是把获取元素写成var checkgread =$('.checkgread')[0];
这样就会报错 提示display未定义 展开
1个回答
展开全部
页面应该是有多个class叫做"checkgread"的元素吧,通过$('.checkgread')获取到的是一个jquery对象数组,加上[0]之后,取到的其实还是一个jquery的对象。所以无法使用原生的js方法,可以试试下面的代码
var checkgread =$('.checkgread')[0][0];
var checkgread =$('.checkgread')[0][0];
追问
还是不行 换了个错误 Cannot set property 'onclick' of undefined
追答
debugger一下啊,看看div1是什么值。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询