[英]I can't get jQuery to work with Bootstrap buttons
Put simply: my goal is to have two buttons on a page, so that "1" is displayed when the first is pressed, and "2" is displayed when the second is pressed. 简而言之:我的目标是在页面上有两个按钮,以便在按下第一个按钮时显示“ 1”,而在按下第二个按钮时显示“ 2”。 This works with radio input, but when I add a button label from Twitter Bootstrap, it no longer works.
这适用于无线电输入,但是当我从Twitter Bootstrap添加按钮标签时,它不再起作用。
First, here is the jquery I am using. 首先,这是我正在使用的jQuery。 I am trying to change the value of the span to the value of the button pressed:
我正在尝试将跨度的值更改为按下的按钮的值:
<span id="val">0</span>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(function() {
$('input[type=radio]').click(function() {
$("#val").html($(this).val());
});
});
</script>
It works fine with this: 它可以正常工作:
<input type="radio" Id="Radio1" value="1" name="a">
<input type="radio" Id="Radio2" value="2" name="a">
But when I do this, it no longer works (I can see and press the buttons, but the value of span remains at 0): 但是,当我这样做时,它将不再起作用(我可以看到并按下按钮,但是span的值保持为0):
<div class="btn-group" data-toggle="buttons">
<label type="button" for="Radio1" class="btn btn-primary active">
<input type="radio" Id="Radio1" value="1" checked>
</label>
<label type="button" for="Radio2" class="btn btn-primary">
<input type="radio" Id="Radio2" value="2">
</label>
</div>
It seems to me like the label tags are causing a problem, but I am unsure why. 在我看来,标签似乎引起了问题,但我不确定为什么。 Removing the labels makes it work, but I need the button labels.
删除标签可以使其正常工作,但是我需要按钮标签。
Place the click event on labels, then find the value on its "input" children: 将click事件放在标签上,然后在其“ input”子元素上找到值:
$(function() {
$('div.btn-group label').click(function() {
$("#val").html($(this).children('input').val());
});
});
JsFiddle: https://jsfiddle.net/5vh3yzzq/1/ JsFiddle: https ://jsfiddle.net/5vh3yzzq/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.