javascript - 如何使用javascript根据输入值隐藏元素?

标签 javascript jquery

我正在尝试根据输入值隐藏/显示输入和 div。

下面的代码不起作用:

HTML:

<div>
     <span class='just-show'>Show This Label</span>
     <input class='for-input' type='text' value='*$set-by-sql-data*'>
</div>

JS

$(document).ready(function () {
    if ($(".for-input").val()=='') {
        $(".just-show").show();
        $(".for-input").hide();
    } else {
        $(".just-show").hide();
        $(".for-input").show();
    }
    return false;
});

如何在没有事件(例如:单击)的情况下隐藏元素?刚刚就绪的功能。

最佳答案

您可以使用

$(document).on('change', 'input', function() {
  // Does some stuff and logs the event to the console
});

或者

$("input").change(function(){
    // Does some stuff and logs the event to the console
});

其中 input 是输入标识符,例如您的 .for-input

您想要的 Jquery 代码:

$(document).on('change', '.for-input', function() {
    if ($(".for-input").val()=='') {
        $(".just-show").show();
        $(".for-input").hide();
    } else {
        $(".just-show").hide();
        $(".for-input").show();
    }
});

示例:

$(document).ready(function () {
    if ($(".for-input").val()=='') {
        $(".just-show").show();
        $(".for-input").hide();
    } else {
        $(".just-show").hide();
        $(".for-input").show();
    }
    //return false;
  
  $(document).on('change', '.for-input', function() {
     if ($(".for-input").val()=='') {
        $(".just-show").show();
        $(".for-input").hide();
    } else {
        $(".just-show").hide();
        $(".for-input").show();
    }
  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div>
     <span class='just-show'>Show This Label</span>
     <input class='for-input' type='text' value='*$set-by-sql-data*'>
</div>

关于javascript - 如何使用javascript根据输入值隐藏元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36230939/

相关文章:

javascript - 使用谷歌图表仪表板中的过滤器聚合数据

javascript - 图像适合屏幕。如何在添加页眉和页脚时删除滚动条

javascript - 根据选择选项隐藏和显示选择选项

javascript - 将 div 设置为固定,直到它与其他元素接触并成为绝对元素。向上滚动时不会恢复为固定状态

javascript - 使用 JQuery 使用 css 属性定位某些 div/li

javascript - 如何仅使用 python 标准库抓取 javascript 网页

javascript - 如何通过上下文检测意图而不是在 Dialogflow 中查询输入

javascript - 带有图像指示器的 Bootstrap 轮播,例如缩略图不起作用

javascript - 两个单独的$.ajax在点击函数上互相调用 "kill"

javascript - 使用 Json 填充剑道树