JavaScript 在输入填充时显示隐藏元素

javascript show hidden element when input is filled

本文关键字:显示 隐藏 元素 填充 输入 JavaScript      更新时间:2023-09-26

嘿,我想在用户填写输入时显示一个表格。

我拥有的是:

在"<head>"部分中:

<script type="text/javascript">
//hide initially    
$("table#mytable").hide();
// show function
function showit() {
$("table#mytable").show();
}
</script>

和表格:

<table id="mytable"><tr><td>FOO</td><td>BAR</td></tr></table>

以及表格下方的表格(也许很重要):

<form action="foobar.php">
<input name="example" onselect="showit()" />
<input type="submit" value="Send" />
</form>

我认为 onselect 并不完美,但它应该在我的情况下做这件事。

上面的代码根本不隐藏表。我不知道我做错了什么。希望有人1能找到错误 - 谢谢。

编辑

这是解决方案:

head

<script type="text/javascript">
function show(id) {
    document.getElementById(id).style.display = 'block';
}
</script>

在每个要隐藏的元素中,只需添加style="display: none;"并编辑输入 - 添加onkeyup="show('id')其中 id 是要隐藏的元素的 id,例如 #mytable

它不起作用的原因是因为你在呈现表元素之前调用了javascript。有三种方法可以做到这一点:

// Use CSS (best):
<table style="display:none;" id="mytable">...</table>

// Using DOM Load event (wait for all of the elements to render) (second best)
$(function() { $("table#mytable").hide(); });

// Put your javascript at the bottom of the page instead of the head. (not preferred)

看看我为你创作的小提琴 - http://jsfiddle.net/ggJSg/

基本上有两个问题:

  • 只有在 DOM 准备就绪时,才需要调用$("#mytable").hide();
  • 使用适当的事件(如我示例中的焦点)来触发表格显示

您也可以使用onkeyup和Document Ready可能会有所帮助

$(document).ready(function() {
 $("#mytable").hide();
   $("#example").keyup(function (e) { 
$("#mytable").show();
}) 
});​

杰菲德尔 http://jsfiddle.net/dznej/

你需要使用 .ready() 函数在 DOM 完成加载时执行代码。然后你应该使用 .change() 函数来显示它:

$(document).ready(function () {
  // Hide initially    
  $('#mytable').hide();
  // When something changes in the input named `example` then show the table.
  $("[name='example']").change(function() {
    $('#mytable').show();
  });
});