-
Notifications
You must be signed in to change notification settings - Fork 139
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
dom操作相关 #33
Comments
// 点击li弹出第几项,不用es6,就是考察的闭包 var dom = document.querySelectorAll('#list li'); dom.forEach(function(dom, index) { (function(index) { dom.addEventListener('click', function(e) { e.stopPropagation(); console.log(index); }); }(index)); }); |
不要给每个 li 都绑一个 listener
|
事件委托 弹窗显示其为当前列表中的第几项
|
@YuanwuHu 强迫症的我很想在alert(i);后面加个break; XD |
@upfain 在第六个后面添加应该是let six = document.querySelectorAll('li')[5]吧 |
let ul = document.getElementById('ul'); |
借用前面几位老哥的答案,整理一下: /**
* 1. 为ul添加一个类bar
* 2. 删除第10个li
* 3. 在第5个li后边添加一个li,文字内容为insert
* 4. 点击任意一个li弹窗显示其为当前列表中第几项
*/
let ul = document.getElementById('list');
let lis = document.getElementsByTagName('li');
// 添加类
ul.className += ' bar';
// 删除第10个li
lis[9].parentNode.removeChild(lis[9]);
// 第6个li后插入li
let tag = document.createElement('li');
tag.innerHTML = 'insert'
lis[6].parentNode.insertBefore(tag, lis[6])
// 点击
ul.addEventListener('click', e=>{
e.stopPropagation();
if (e.target.tagName.toLowerCase() === 'li'){
let lis = document.getElementsByTagName('li');
lis = [].slice.call(lis)
alert(lis.indexOf(e.target))
}
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
<ul>
添加一个类 bar<li>
<li>
后面增加一个<li>
, 其文字内容为<v2ex.com />
<li>
弹窗显示其为当前列表中的第几项。要求:使用原生JS
发现没有还没dom操作的问题,这道题是从https://www.v2ex.com/t/328943?p=1 这里抄来的。
The text was updated successfully, but these errors were encountered: