Javascript条件输入id语句

标签 javascript jquery if-statement jquery-selectors

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

<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 专家而且它不起作用,任何人都可以提供帮助?? 非常感谢...

最佳答案

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

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

关于Javascript条件输入id语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16297679/

相关文章:

javascript - Magento 1.9.2 - 更新可配置产品流程中的自定义属性 'delivery_time'

javascript - 淡化整个窗口 - 然后加载 URL?

javascript - 如何自动点击按钮(模拟鼠标点击加载)?

php - 用 PHP 中的逻辑表达式替换 IF

使用 CoffeeScript 语法的 JavaScript - if 条件 : optimize if statement structure

javascript - 更改可变文本颜色

javascript - 表单数据未发送到服务器

jQuery 延迟和隐藏元素

javascript - Javascript 中的动态表和事件委托(delegate)

jquery - django.jQuery $ 不是函数消息