无需点击即可触发单选按钮点击
Trigger radio button click without the click
我有两个自定义样式的单选按钮,如下所示[只是一个示例]
li {
width: 100px;
border: 1px solid black;
display: inline-block;
}
<ul>
<li>
<input type="radio" name="radio-test" id="radio1">
<div>
<label for="radio1">Radio One</label>
</div>
</li>
<li>
<input type="radio" name="radio-test" id="radio2">
<div>
<label for="radio2">Radio Two</label>
</div>
</li>
</ul>
一旦这看起来更漂亮,我希望在包含单选按钮的框内的任意位置单击应该触发该选择的激活。
我的队友使用自定义样式和图像来显示选择,因此我不想修改 CSS。
我在想办法用 Javascript 实现上述功能。
攻击 li
上的 click
事件处理程序并触发底层 input
上的 click
但这会导致事件触发器无限递归。
这让我想到了 2 个问题:
Is there a way to stop the the click recursion? I tried preventDefault
and stopPropagation
on the JS triggered click but
they do not seem to accomplish what I want.
Can we user JavaScript(or jQuery if needed) to differentiate between a real mouse click and a JS triggered click event?
你走在正确的轨道上。您只需要停止从输入返回到列表项的传播:
$('li').click(function() {
$(this).find('input').click()
})
$('input').click(function(e) {
e.stopPropagation();
})
li {
width: 100px;
border: 1px solid black;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li>
<input type="radio" name="radio-test" id="radio1">
<div>
<label for="radio1">Radio One</label>
</div>
</li>
<li>
<input type="radio" name="radio-test" id="radio2">
<div>
<label for="radio2">Radio Two</label>
</div>
</li>
</ul>
我有两个自定义样式的单选按钮,如下所示[只是一个示例]
li {
width: 100px;
border: 1px solid black;
display: inline-block;
}
<ul>
<li>
<input type="radio" name="radio-test" id="radio1">
<div>
<label for="radio1">Radio One</label>
</div>
</li>
<li>
<input type="radio" name="radio-test" id="radio2">
<div>
<label for="radio2">Radio Two</label>
</div>
</li>
</ul>
一旦这看起来更漂亮,我希望在包含单选按钮的框内的任意位置单击应该触发该选择的激活。
我的队友使用自定义样式和图像来显示选择,因此我不想修改 CSS。
我在想办法用 Javascript 实现上述功能。
攻击 li
上的 click
事件处理程序并触发底层 input
上的 click
但这会导致事件触发器无限递归。
这让我想到了 2 个问题:
Is there a way to stop the the click recursion? I tried
preventDefault
andstopPropagation
on the JS triggered click but they do not seem to accomplish what I want.Can we user JavaScript(or jQuery if needed) to differentiate between a real mouse click and a JS triggered click event?
你走在正确的轨道上。您只需要停止从输入返回到列表项的传播:
$('li').click(function() {
$(this).find('input').click()
})
$('input').click(function(e) {
e.stopPropagation();
})
li {
width: 100px;
border: 1px solid black;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li>
<input type="radio" name="radio-test" id="radio1">
<div>
<label for="radio1">Radio One</label>
</div>
</li>
<li>
<input type="radio" name="radio-test" id="radio2">
<div>
<label for="radio2">Radio Two</label>
</div>
</li>
</ul>