首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如果隐藏表单包含id='style‘的输入,则在javascript中设置display='block’后将不可见

如果隐藏表单包含id='style‘的输入,则在javascript中设置display='block’后将不可见
EN

Stack Overflow用户
提问于 2018-12-17 04:29:15
回答 3查看 54关注 0票数 2

考虑以下代码:

代码语言:javascript
复制
<form id='f' style='display: none'>
	<input type='text' id='style'/>
</form>

<button onclick='document.getElementById("f").style.display = "block"'>Click</button>

在点击按钮后,我希望表单变得可见,但它不是。为什么呢?

请注意,如果以下条件之一为真,它将按预期工作:

输入输入id未命名为"style"

  • another标记,例如使用div而不是
  • 输入使用非表单元素标记来代替输入(例如,p或div等标记可以很好地使用;输入、文本区域和按钮不能使用)
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-12-17 04:39:29

表单中的控件元素也会成为表单元素的属性。因此,通过使用style作为其id,可以使<form>style属性引用一个输入。

如果添加console.log(document.getElementById('f').style),它将返回<input id="style">,而不是元素的预期样式规则

我会将窗体包装在一个容器中,并将内联样式应用于该容器。很少会使用<form>作为块元素

代码语言:javascript
复制
<div id="f" style='display: none'>
  <form>
    <input type='text' id='style' />
  </form>
</div>
<button onclick='document.getElementById("f").style.display = "block"'>Click</button>

票数 3
EN

Stack Overflow用户

发布于 2018-12-17 04:42:57

这是因为通过在子元素中使用' id =' style‘,您将创建对该子元素的引用,而不是访问父元素的样式,以便修复您应该为id使用不同的名称。

示例:https://jsfiddle.net/kwz3v9fx/2/

代码语言:javascript
复制
<form id='f' style='display: none'>
  <input type='text' id='anotherName'/>
</form>
    
<button onclick='document.getElementById("f").style.display = "block"'>Click</button>

票数 1
EN

Stack Overflow用户

发布于 2018-12-17 04:52:15

这是因为内联样式(style="display: none;")优先于内部样式(document.getElementById("f").style.display = "block")。要解决此问题,请改用setAttribute

代码语言:javascript
复制
<form id='f' style='display: none'>
	<input type='text' id='style'/>
</form>

<button onclick='document.getElementById("f").setAttribute("style", "display: block;")'>Click</button>

您可以看到这是因为<form>元素在JavaScript中被视为对象,并且当子元素具有nameid属性时,该属性将作为属性添加到form对象。请看下面的代码片段:

代码语言:javascript
复制
console.log(document.getElementById("f").style); 
/*This shows the <input> element rather than the styles 
applied to the actual <form> element*/
代码语言:javascript
复制
<form id="f">
    <input type="text" id="style" />
</form>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53806208

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档