Javascript 通过单击其标签来切换 HTML 单选按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4213172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:24:51  来源:igfitidea点击:

Toggle HTML radio button by clicking its label

javascripthtmlradio-button

提问by Alexander Farber

Is there please a simple way to make a radio button toggle - when a text near it is clicked - without introducing any big Javascript Framework into my smal PHP project?

是否有一种简单的方法可以使单选按钮切换 - 当单击它附近的文本时 - 而不会在我的小型 PHP 项目中引入任何大型 Javascript 框架?

The web form looks like this:

Web 表单如下所示:

<html>
<body>
<form method="post">
<p>Mode:<br /> 
<input type="radio" name="mode" value="create"><i>create table</i><br />
<input type="radio" name="mode" value="select" checked>select records (can specify id)<br />
<input type="radio" name="mode" value="insert">insert 1 record (must specify all)<br />
<input type="radio" name="mode" value="delete">delete records (must specify id)<br />
<input type="radio" name="mode" value="drop"><i>drop table</i><br />
</p>
<p>Id: <input type="text" name="id" size=32 maxlength=32 /> (32 hex chars)</p>

<p>Latitude: <input type="text" name="lat" size=10 /> (between -90 and 90)</p>
<p>Longitude: <input type="text" name="lng" size=10 /> (between -90 and 90)</p>
<p>Speed: <input type="text" name="spd" size=10 /> (not negative)</p>
<p><input type="submit" value="OK" /></p>
</form>
</body>
</html>

回答by Nick Craver

You can also wrap your elements withoutgiving them each an ID, since a <label>is implicitly for the input it contains, like this:

您还可以包装您的元素而不给它们每个 ID,因为 a<label>隐式表示它包含的输入,如下所示:

<label>
   <input type="radio" name="mode" value="create">
   <i>create table</i>
</label>

回答by Frédéric Hamidi

You can use <label>elements, which are designed to do exactly that:

您可以使用<label>元素,这些元素旨在做到这一点:

<input type="radio" id="radCreateMode" name="mode" value="create" />
<label for="radCreateMode"><i>create table</i></label>

回答by Jason Ching

Wrapping the input under the label should work.

将输入包装在标签下应该有效。

<label>
    <input type="radio" name="mode" value="create"><i>create table</i>
</label>

回答by Christopher Grigg

I had trouble finding the value of the radio button using this method, an alternative is to use a hit area increasing clickable area of a button.

我无法使用此方法找到单选按钮的值,另一种方法是使用增加按钮的可点击区域的点击区域