模拟标签点击按钮点击

问题描述:

请点击按钮,我需要模拟标签点击的帮助。 我试图使标签的大小与按钮相同,所以当我点击按钮时它会检查我的复选框,然后我尝试使用java脚本来模拟标签点击时,我点击按钮。 问题是我的标签尺寸是在我的按钮内部很小,所以我必须点击标签内部进行检查。模拟标签点击按钮点击

这是我的HTML文件:

{%- block checkbox_widget -%} 
<button class="btn-large waves-effect waves-light {% if checked %}disabled{% endif %}" style="margin-bottom:2%;"> 
    <input type="checkbox" {{ block('widget_attributes') }}{% if value is defined %} value="{{ value }}"{% endif %}{% if checked %} checked="checked"{% endif %} /> 
    <label for="{{ id }}" class="white-text" style="font-size: 22px;">{{ label|trans({}, translation_domain) }}</label> 
</button> 
{%- endblock checkbox_widget -%} 

{%- block radio_widget -%} 
<button class="btn-large waves-effect waves-light {% if checked %}disabled{%endif %}" style="margin-bottom:2%;"> 
    <input type="radio" {{ block('widget_attributes') }}{% if value is defined %} value="{{ value }}"{% endif %}{% if checked %} checked="checked"{% endif %} /> 
    <label for="{{ id }}" class="white-text" style="font-size: 22px;">{{ label|trans({}, translation_domain) }}</label> 
</button> 
{%- endblock radio_widget -%} 

我使用了以下修改+脚本

{%- block checkbox_widget -%} 

<button class="btn-large waves-effect waves-light {% if checked %}disabled{% endif %}" id="button" onclick="myFunction()" style="margin-bottom:2%;"> 
    <input type="checkbox" {{ block('widget_attributes') }}{% if value is defined %} value="{{ value }}"{% endif %}{% if checked %} checked="checked"{% endif %} /> 
    <label for="{{ id }}" class="white-text" style="font-size: 22px;" id="check">{{ label|trans({}, translation_domain) }}</label> 
</button> 

<script> 
    function myFunction() { 
     buttn = document.getElementById("check"); 
     buttn.click(); 
    } 
</script> 
{%- endblock checkbox_widget -%} 

可有人请纠正我的Java脚本或告诉我怎么把我的标签同样大小尝试作为我的按钮。 对不起,事先我的英语和感谢:)

+2

为什么你使用''里面''

+2

这不是有效的HTML标记 –

{%- block checkbox_widget -%} 

     <button class="btn-large waves-effect waves-light {% if checked %}disabled{% endif %}" id="button" onclick="myFunction()" style="margin-bottom:2%;"></button> 
     <input type="checkbox" {{ block('widget_attributes') }}{% if value is defined %} value="{{ value }}"{% endif %}{% if checked %} checked="checked"{% endif %} /> 
     <label for="{{ id }}" class="white-text" style="font-size: 22px;" id="check">{{ label|trans({}, translation_domain) }}</label> 


    <script> 
    function myFunction() { 
    buttn = document.getElementById("check"); 
    buttn.click(); 
    } 
</script> 
    {%- endblock checkbox_widget -%} 

试试这个

第一:你把页面上的这些小部件的不止一个?如果是这样,它将不会按照您预期的方式工作,因为id对于单个元素应该是唯一的。其次:由于您的标签绑定到复选框(通过for属性),所以如果您单击标签,它看起来好像什么也没有发生,因为JS正在发送点击,那么标签是“撤消“它。请参阅:https://jsfiddle.net/q1vour7v/并单击标签,然后单击远离标签的边缘。

在这个版本中,标签是不依赖于对应的复选框,它按预期工作:https://jsfiddle.net/q1vour7v/1/