开发者

Getting the label of "this" in jQuery

The following is my code for changing the color of the label of the input field in focus:

    $(document).ready(function() {

var name = $(this).attr("name");

$(".comm-input").focus(function() {
    $("label[for=name]").css({"color" :"#669900"});
}); 

$(".comm-input").blur(function() {
    $("label[for=name开发者_运维问答]").css({"color" :"#999999"});
});     

});

.comm-input is the class of the input. Any ideas on why its not working?? Thanks!


You have a couple of issues.

Firstly, you're defining name in ready(). It won't have any (relevant) meaning there. The correct place to find that is inside your event handlers.

Secondly, you're not substituting the value of name, you're using the literal name. You want:

$(function() {
  $(".comm-input").focus(function() {
    $("label[for" + this.name + "]").css({"color" :"#669900"});
  }).blur(function() {
    $("label[for=" + this.name + "]").css({"color" :"#999999"});
  }); 
});

Lastly, I'd strongly suggest using a CSS class instead of directly setting CSS style attributes. They are problematic to remove. For example, what if the normal color is green? Your code will set it to something else it wasn't but removing a class will set it correctly so CSS:

label.highlight { color: #690; }

with:

$(function() {
  $(".comm-input").focus(function() {
    $("label[for" + this.name + "]").addClass("highlight");
  }).blur(function() {
    $("label[for=" + this.name + "]").removeClass("highlight");
  }); 
});


You need to change your selector to this:

$(".comm-input").focus(function() {
     $("label[for=" + this.name + "]")).css("color", "#669900");
});     

It won't automatically change the string literal "name" with the value of your name variable.

Also, when you were grabbing the name variable, this refers to the document, not to the element being focused.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜