jQuery是()选择器不呈现结果

时间:2015-12-27 06:49:34

标签: javascript jquery

我正在使用is()选择器,它必须为我提供一些结果,但它还没有发生。

HTML:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("div p").is(":nth-child(2)").css("border","2px solid red");

    });
});
</script> 
</head>
<body>
    <button>Click Me!</button>
    <p>This is a paragraph.</p>
    <p>This is a paragraph.</p>
    <p>This is a paragraph.</p>
    <p>This is a paragraph.</p>
    <p>This is a paragraph.</p>
    <div>
        <p>This is a paragraph.</p>
        <p>This is a paragraph.</p>
        <p>This is a paragraph.</p>
        <p>This is a paragraph.</p>
        <p>This is a paragraph.</p>
    </div> 
    <div>
        <p>This is a paragraph.</p>
        <p>This is a paragraph.</p>
        <p>This is a paragraph.</p>
        <p>This is a paragraph.</p>
        <p>This is a paragraph.</p>
    </div> 
</body>
</html>

期望:

我期待两行是红色(第7和第12段),但我得到一个错误。

错误:

  

Uncaught TypeError:$(...)。is(...)。css不是函数

注:

  

我想只使用.is()选择器。

有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:3)

您应该按如下方式编写。因为.is()会给你一个不能有.css()函数的布尔值。

$("div p:nth-child(2)").css("border","2px solid red");

<强>更新

可能这样

WORKING FIDDLE

$("div p").each(function(){
    if($(this).is(":nth-child(2)"))
    {
        $(this).css("border","2px solid red");
    }
});