1

我让这段代码完美运行,用图像模拟预填充输入字段:

<script>
$('#example).focus(function(){
    var newValue = $(this).val();
    if ($(this).val() == ""){
        $(this).css("background-image", "none");
    }else{
        $(this).val(newValue);
    }
}).blur(function(){
    var newValue = $(this).val();
    if ($(this).val() == ""){
             $(this).css("background-image", "url(assets/templates/herveou-coiffure/css/pre_input.png)");
}else{
        $(this).val(newValue);
    }
});
</script>

我需要用很少的输入字段(至少2个)来使用它,所以我尝试了这样的事情:

<script>
$('#example, example2').focus(function(){
    var newValue = $(this).val();
    if ($(this).val() == ""){
        $(this).css("background-image", "none");
    }else{
        $(this).val(newValue);
    }
}).blur(function(){
    var newValue = $(this).val();
    if ($(this).val() == ""){
       if ($('#example2')[0]){
   // Do something here if an element with this class exists
 $(this).css("background-image", "url(assets/templates/herveou-coiffure/css/headers.jpg)");}
       if ($('#example')[0]){
   // Do something here if an element with this class exists
 $(this).css("background-image", "url(assets/templates/herveou-coiffure/css/pre_input.png)");}
}else{
        $(this).val(newValue);
    }
});
</script>

当然,我不是 javascritp 专家,它不起作用,任何人都可以帮忙??非常感谢...

4

2 回答 2

4

每次选择 ID 时,都需要记住使用 ID 选择器#

您需要使用$('#example, #example2')而不是$('#example, example2').

于 2013-04-30T10:29:24.043 回答
0

当你写 $('<selector1>, <selector2> , ....'. 您应该在每个参数中编写适当的选择器。所以你应该改变$('#example, example2')$('#example, #example2').

于 2013-04-30T12:22:44.147 回答