提问者:小点点

使用高级选择器执行以下任务的JQuery代码。 PS:cihldren()不工作


如何才能只显示前两个列表项目,以及,如何使背景颜色的孩子下

标记为绿色。 仅使用JQUERY

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Advanced Selectors</title>
    <script type="text/javascript" src="jquery-3.5.0.js"></script>
    <script type="text/javascript" src="index.js"></script>
</head>
<body>
    <p id="intro">jQuery is a lightweight, "write less, do more" JavaScript library.
        <h6>The purpose of jQuery is to make it much easier to use
             JavaScript on your website</h6>
    </p>
    <ol>
        <li>HTML/DOM manipulation</li>
        <li>CSS manipulation</li>
        <li>Effects and animations</li>
        <li>AJAX</li>
    </ol>
</body>
</html>

我的JQuery代码不工作

$(document).ready(()=>{
   //Code to make children of P to green 
   $("p").children().css('background-color:green');
   //Code to display only first 2 items of list

})

共1个答案

匿名用户

这里要提到为什么您的代码不能工作,首先是因为您不能在p-tag中包含h6-tag。

其次,你写道:

$("p").children().css('background-color:green');

最好像这样遍历每个子项(注意,您将css()-函数中的值写错了):

$("#intro").children().each(function(){
  $(this).css("background-color", "green");
});

当只显示两个列表项时,您可以这样做:

$("ol").children().each(function() {
index = $(this).index();
if (index > 1) {
  $(this).hide();
}

jsfiddle:https://jsfiddle.net/boe2sdyk/