Javascript条件输入id语句

Javascript condition input id statement

本文关键字:语句 id 输入 条件 Javascript      更新时间:2023-09-26

我让这段代码完美地工作,以模拟带有图像的预填充输入字段:

<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>

当然我不是javascript专家,它不起作用,任何人都可以帮助??

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

你需要用$('#example, #example2')代替$('#example, example2')

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