以前写循环遍历习惯性用 for(){},但是这次突然觉着无从下手了。
场景一:左侧九宫格菜单(显示栏),需要遍历获取每个菜单的id,然后放到数组里。
下面是要遍历的HTML代码:<section id="menuGrid" class="menug col-sm-12 "><div class="circlew"><div id="Cate101" class="col-sm-4 col-xs-6 circle"><img src="img/wxhtml/kszl.png" /><p>科室信息</p><span class="glyphicon glyphicon-minus-sign hide"></span></div><div id="Cate102" class="col-sm-4 col-xs-6 circle"><img src="img/wxhtml/kszl.png" /><p>健康知识</p><span class="glyphicon glyphicon-minus-sign hide"></span></div></div></section
用for循环的时候,得不到想要的效果
for (var i = 0; i < $('#menuGrid .circlew div').length; i++) {if ($(this).attr('id') != undefined) {//id为undefined时,substr报错console.log('ceshi:' + $(this).attr('id').substr(4));}}
每个id都输出了8次,这个地方我就不知道要怎么样用for循环将这些div进行遍历了,真的是基础不牢固吧,请大家指教一下。
下面是我用each()的实现方法。
$(selector).each(function(index,element)):规定为每个匹配元素规定运行的函数。
$('#menuGrid .circlew div').each(function () {console.log($(this).attr('id'));})
场景二:点击左侧的加号,出现右侧编辑栏里没有选中的选项,左边移除不想要的选项到了右边,再点击加号,就需要遍历右边已有的所有元素,对比已有的元素,重复的不添加(因为这里做的是点击加号就需要加载一次一开始没有选中的选项)
$('#showMenu .addmenu div').each(function () {var RemoveText = $(this).text().trim();//对比的是div的文本内容console.log(RemoveText);$('#showMenu .addmenu div:contains(' + RemoveText + ')').remove();
})
//这里也涉及到一个我以前没接触过的知识点 :contains 选择器选取包含指定字符串的元素。
//该字符串可以是直接包含在元素中的文本,或者被包含于子元素中。
//$(":contains(text)")
经常与其他元素/选择器一起使用,来选择指定的组中包含指定文本的元素
最终效果图: