Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/436.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 元素发生但非';t儿童_Javascript_Jquery_Html - Fatal编程技术网

Javascript 元素发生但非';t儿童

Javascript 元素发生但非';t儿童,javascript,jquery,html,Javascript,Jquery,Html,我需要为超过某个阈值的每个元素添加一个内联样式。要以代码格式解释这一点,我的示例如下: var listItems = $(".subitem"); listItems.each(function(index, value) { console.log(listItems.length); if (listItems.length > 5) { // for every ".subitem" that is the 6th,

我需要为超过某个阈值的每个元素添加一个内联样式。要以代码格式解释这一点,我的示例如下:

var listItems = $(".subitem");
    listItems.each(function(index, value) {
        console.log(listItems.length);
        if (listItems.length > 5) {
            // for every ".subitem" that is the 6th, 7th or however many but
            // beyond the fifth, inject an inline style
        }
 }
我的第一个想法是
nth child
nth类型
,但它们都是不正确的,因为标记大致如下所示:

<div>
  <div class="subitem"></div>
</div>
<div>
  <div class="subitem"></div>
</div>
<div>
  <div class="subitem"></div>
</div>


有了这种标记结构(无法更改),我如何才能最好地遍历
.subitem
的每个实例,并将内联样式添加到超出限制的引用中?

如此接近。如您所见,当您循环遍历列表项时,会传入索引。如果看到索引超过4(即第5个元素之后),则可以使用jquery应用所需的样式

var listItems = $(".subitem");
    listItems.each(function(index, value) {
        if (index > 4) {
            // apply styling specific to elements 6 and beyond
        }
 }

如此接近。如您所见,当您循环遍历列表项时,会传入索引。如果看到索引超过4(即第5个元素之后),则可以使用jquery应用所需的样式

var listItems = $(".subitem");
    listItems.each(function(index, value) {
        if (index > 4) {
            // apply styling specific to elements 6 and beyond
        }
 }
可以使用选择器进行筛选,或排除低于该值集的索引

listItems.filter(':gt(4)').each(function(){
   $(this).doSomething()       
})
// or
$(".subitem:gt(4)").each(function(){...
// or using slice()
listItems.slice(4).each(function(){
可以使用选择器进行筛选,或排除低于该值集的索引

listItems.filter(':gt(4)').each(function(){
   $(this).doSomething()       
})
// or
$(".subitem:gt(4)").each(function(){...
// or using slice()
listItems.slice(4).each(function(){

您正在检查长度是否大于6,而不是检查元素本身是否超过6

由于参数'index'是您在此moment中迭代的元素的位置,因此您应该使用它:

   var listItems = $(".subitem");
listItems.each(function(index, value) {
    if (index > 5) {
        $(this).css("color","red");
    }
 });

您正在检查长度是否大于6,而不是检查元素本身是否超过6

由于参数'index'是您在此moment中迭代的元素的位置,因此您应该使用它:

   var listItems = $(".subitem");
listItems.each(function(index, value) {
    if (index > 5) {
        $(this).css("color","red");
    }
 });

console.log(listItems.length)?您不应该改为跟踪
index
console.log(listItems.length)?您不应该改为跟踪
索引吗?只添加了另一个
slice()
只添加了另一个
slice()