javascript - 要取 指定索引的ul 里的 所有l(wèi)i 怎么取
問題描述
要取 指定索引的ul 里的 所有l(wèi)i 怎么取
我想這么寫var afterUl=document.querySelectorAll(’ul’)[sy-1];var afterLi=afterUl.querySelectorAll(’li’);但是下面的一行會(huì)報(bào)錯(cuò)leilei.html:128 Uncaught TypeError: Cannot read property ’querySelectorAll’ of undefined。。。我應(yīng)該怎么寫。。新手求助
問題解答
回答1:----- 06-03 14:50 -----
感謝 jasonintju 指出錯(cuò)誤。
這里的報(bào)錯(cuò)并不是因?yàn)闆]有 querySelectorAll 方法,是由于題主的 下標(biāo) 越界了,導(dǎo)致取到的 是 undefined,undefined 沒有 querySelectorAll 方法,故報(bào)錯(cuò)。
正確的下標(biāo)寫法是沒有問題的。
補(bǔ)充文檔Element.querySelectorAll() - Web APIs | MDN
----- 06-03 04:30 -----
leilei.html:128 Uncaught TypeError: Cannot read property ’querySelectorAll’ of undefined
報(bào)錯(cuò)信息已經(jīng)給你提示了,不能讀取querySelectorAll屬性,因?yàn)樗?undefined
原因是因?yàn)?querySelectorAll 是 document的方法,而不是 element的方法。
var afterUl = document.querySelectorAll(’ul’)[0];// document.querySelectorAll(’ul’) 通過 document 的方法 querySelectorAll 得到了當(dāng)前文檔下的所有 ul 元素,是一個(gè) NodeList 類數(shù)組。之后假設(shè)通過 [0] 取到了這個(gè) NodeList 中的第一個(gè)元素,那么 afterUl 這個(gè)變量指向的是一個(gè) DOM 元素,也就是 elementvar afterLi=afterUl.querySelectorAll(’li’);// 這時(shí)用 afterUl 也就是一個(gè) element 調(diào)用 querySelectorAll,由于 element 下沒有 querySelectorAll 這個(gè)方法 自然就報(bào)錯(cuò)了
解決方案是使用 getElementsByTagName
var oUl = document.getElementsByTagName(’ul’)[0];var aLi = oUl.getElementsByTagName(’li’);
可以參考一下 JavaScript 文檔中關(guān)于這兩個(gè) API 的介紹
Document.querySelectorAll - Web API 接口 | MDNelement.getElementsByTagName - Web API 接口 | MDN
或者使用 jQuery 的
var aLi = $(’ul’).eq(0).find(’li’);回答2:
實(shí)現(xiàn)的方式很多,你可以采用原生JavaScript,也可以用各種js庫來實(shí)現(xiàn)。這里采用原生JavaScript整理一個(gè)思路,在ul的DOM元素上添加一個(gè)id屬性,通過document.getElementById取出ul,然后通過getElementsByTagName取出li元素。
代碼如下:
<ul id='ul-wrap'> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li></ul>var ul_wrap = document.getElementById(’ul-wrap’);var li_item = ul_wrap.getElementsByTagName(’li’);console.log(ul_wrap);console.log(li_item);回答3:
let oLis = document.getElementsByTagName('ul')[index].getElementsByTagName('li');
回答4:我自己找到錯(cuò)誤了,是因?yàn)槲液竺娴乃饕齕sy-1]中變量sy的是之前遍歷所有l(wèi)i時(shí)候賦值的,因?yàn)樗衛(wèi)i比所有ul多很多,所以[sy-1]超過了ul的個(gè)數(shù),上面那行就會(huì)undefined 下面那行就報(bào)錯(cuò)了。謝謝大家。。這問題太幼稚。。
相關(guān)文章:
1. 求救一下,用新版的phpstudy,數(shù)據(jù)庫過段時(shí)間會(huì)消失是什么情況?2. mysql - 如何在有自增id的情況下,讓其他某些字段能不重復(fù)插入3. django - Python error: [Errno 99] Cannot assign requested address4. python小白 關(guān)于類里面的方法獲取變量失敗的問題5. angular.js - 百度支持_escaped_fragment_嗎?6. Python2中code.co_kwonlyargcount的等效寫法7. [python2]local variable referenced before assignment問題8. node.js - win 下 npm install 遇到了如下錯(cuò)誤 會(huì)導(dǎo)致 無法 run dev么?9. python小白,關(guān)于函數(shù)問題10. javascript - webpack1和webpack2有什么區(qū)別?
