简体   繁体   English

如何将错误/信息div与其上方的文本框链接

[英]How do I link an error/information div with a textbox above it

I have a pretty standard html form with a few input boxes. 我有一个非常标准的html表单,有几个输入框。 I have a small div under each textbox that displays directions when the textbox has focus (the rest of the time they are hidden). 我在每个文本框下面都有一个小div,它在文本框具有焦点时显示方向(其余时间它们被隐藏)。 The divs can also change color and display error messages. div还可以更改颜色并显示错误消息。

I would like to be able to have one javascript function to show directions on focus, one function to show errors on blur, one function to hide directions/errors etc. 我希望能够有一个javascript函数来显示焦点方向,一个函数显示模糊错误,一个函数隐藏方向/错误等。

The problem that I am running into is how to best associate the textboxes and their respective divs. 我遇到的问题是如何最好地关联文本框和它们各自的div。 I have used a naming convention in which I gave the textboxes an ID like field1 and then called their div field1Div . 我使用了一个命名约定,其中我给文本框一个像field1这样的ID,然后调用它们的div field1Div This worked OK but something tells me there is a better way to do this. 这工作正常,但有些东西告诉我有更好的方法来做到这一点。

What is the "correct" way to associate the div and textbox? 关联div和文本框的“正确”方法是什么?

Labels might be the better way to go but if you want to use Divs - you can use something like this: 标签可能是更好的方法,但如果你想使用Divs - 你可以使用这样的东西:

<html>
<head>
<script>
    function giveDirections(obj){  
obj.nextElementSibling.style.display="block"                
    }
    function hideDirections(obj){
    obj.nextElementSibling.style.display="none"
    }
    </script>
    </head>
<body>
    <input id="test" name="test" onfocus="giveDirections(this)" onblur="hideDirections(this)" />
    <div style="display:none">Hi I am some directions</div>
    </body>
</html>

http://jsfiddle.net/zq533/8/ http://jsfiddle.net/zq533/8/

using this.nextElementSibling - but I am not sure every browser supports - I tried it on FF,IE and Chrome and it worked. 使用this.nextElementSibling - 但我不确定每个浏览器是否支持 - 我在FF,IE和Chrome上试过它并且它有效。

I am sure there is a better way. 我相信有更好的方法。

You may define custom attributes for input boxes. 您可以为输入框定义自定义属性。

<html>
<head>
<script>
    function showHint(obj){  
        document.getElementById(obj.getAttribute("hintbox")).style.visibility = "visible";                  
    }
    function hideHint(obj){
        document.getElementById(obj.getAttribute("hintbox")).style.visibility = "hidden";  
    }
    </script>
    </head>
<body>
    <input hintbox="div1" onfocus="showHint(this)" onblur="hideHint(this)" />
    <div id="div1" style="visibility:hidden">hint 1</div>
    <input hintbox="div2" onfocus="showHint(this)" onblur="hideHint(this)" />
    <div id="div2" style="visibility:hidden">hint 2</div>
    </body>
</html>​

http://jsfiddle.net/YhefV/ http://jsfiddle.net/YhefV/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM