jQuery classe Selector有多个元素

时间:2016-02-23 21:37:50

标签: javascript jquery

你好我只是想突出第一个元素......

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
     var $element = $(".intro");
     $element[0].css("bbroswerackground-color", "yellow");
});
</script>
</head>
<body>

<h1>Welcome to My Homepage</h1>

<p class="intro">This paragraph has class "intro".</p>
<p>This is a paragraph.</p>
<p class="intro">This paragraph has class "intro".</p>
<p>This is another paragraph.</p>
<p class="intro">This paragraph has class "intro".</p>

</body>
</html>

3 个答案:

答案 0 :(得分:2)

这应该有效:

$(".intro").eq(0).css("background-color", "yellow");

编辑:你的背景语法有错误。

编辑2:请下次自己搜索

答案 1 :(得分:0)

如果您希望在第一个元素上应用/设置某些属性。

使用.first()过滤器

 $(".intro").first().css("background-color", "yellow");

示例:https://jsfiddle.net/DinoMyte/4y80has5/

使用:first选择器:

 $(".intro:first").css("background-color", "yellow");

示例:https://jsfiddle.net/DinoMyte/4y80has5/1/

答案 2 :(得分:0)

你也可以在没有JQuery的情况下使用CSS3选择器这样做:

<!DOCTYPE html>
<html>
<head>
<style>
    p.intro:first-of-type {
        color:red;
    }
</style>
</head>
<body>

<h1>Welcome to My Homepage</h1>

<p class="intro">This paragraph has class "intro".</p>
<p>This is a paragraph.</p>
<p class="intro">This paragraph has class "intro".</p>
<p>This is another paragraph.</p>
<p class="intro">This paragraph has class "intro".</p>

</body>
</html>