2

我很难理解为什么某个特定的选择器不适合我。诚然,我是一个 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 :first'、'.editbox div:first' 等变体。

本质上,我希望能够可靠地测试这是类名的第一个还是最后一个元素。

谢谢!

编辑:这是我正在使用的 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 执行此操作的正确方法。

4

4 回答 4

2

如果您希望鼠标悬停在 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");
})
于 2009-05-20T16:13:52.630 回答
2

更新:这适用于第一个元素。

$('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");
}
于 2009-05-20T16:19:19.390 回答
0

你试过了吗

if ($(this).is(':first')) {$(this).css("border", "1px solid red");}
于 2009-05-20T16:16:19.317 回答
0
    $('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");
    })
于 2009-05-20T16:38:36.713 回答