我很难理解为什么特定的选择器不适合我。不可否认,我是一个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学习正确的方法。
答案 0 :(得分: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");
})
答案 1 :(得分: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");
}
答案 2 :(得分:0)
你试过吗
if ($(this).is(':first')) {$(this).css("border", "1px solid red");}
答案 3 :(得分: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");
})