我难以理解为什么一个特定的选择是不是为我工作。诚然我有点一个jQuery新手的。

此正确地选择在第一的页面和颜色上div.editbox它黄色:

$('div.editbox:first').css("background-color","yellow");

然而,该构建体if ... is使得高亮框出现的每个框,因为它是鼠标悬停。

$('div.editbox').bind('mouseover', function(e) {
    if ($(this).is('div.editbox:first')) {$(this).css("border", "1px solid red");}
});

我试图变体如 '.editbox:第一', '.editbox DIV:第一' 等

基本上,我想能够可靠地测试这是否是与类名称的第一个或最后一个元素。

谢谢!

编辑:这里是我使用的HTML:

<body>
<div class="container">
<p></p>
<div class="editbox" id="box1">Foo</div>
<div class="editbox" id="box2">Bar</div>
<div class="editbox" id="box3">Baz</div>
<div class="responsebox" id="rbox"></div>
</div>
</body>

这仅仅是一个证明的概念页;当然,实际的页面会更加复杂。还是那句话:我要的是,如果我在第一个或最后一个“div.editbox”可靠地检测。我用一种解决方法是:

$('div.editbox:last').addClass("lasteditbox");

然后测试if ($(this).is(".lasteditbox"))其工作原理,但似乎笨拙,我努力学习的正确方法使用jQuery做到这一点。

有帮助吗?

解决方案

<强>更新:这适用于第一元件

$('div.editbox').bind('mouseover', function(e) {
 if ($("div.editBox").index(this) == 0) {
      $(this).css("border", "1px solid red");
    }
});

和最后元件,此选择器的工作原理:

if($("div.editBox").index(this) == ($("div.editBox").length-1)){
     $(this).css("color","red");
}

其他提示

如果你想在里面的div类编辑框的只是第一次出现的鼠标悬停

$('div.editbox:first').mouseover(function() {
   $(this).css("border", "1px solid red");
});

修改

$('div.editbox').mouseover(function() {
   $(this).css("border", "1px solid yellow");
}).filter(':first').mouseover(function(){
  $(this).css("border", "1px solid red");
}).filter(':last').mouseover(function(){
  $(this).css("border", "1px solid blue");
})

具有u试图

if ($(this).is(':first')) {$(this).css("border", "1px solid red");}
    $('div.editbox').mouseover(function() {
       //change the css for all the elements
       $(this).css("background-color", "yellow");
    })
    .filter(':first,:last').mouseover(function(){
      //execlude the first and the last
      $(this).css("background-color", "Blue");
    })
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top