我正在尝试为一组设置创建一个jquery事件侦听器。这是单选按钮的示例:
<div class="settings">
<input type="radio" id="a1" name="a" value="1" style="display: none;" />
<label for="a1">a1</label>
<input type="radio" id="a2" name="a" value="2" style="display: none;" />
<label for="a2">a1</label>
<input type="radio" id="a3" name="a" value="3" style="display: none;" />
<label for="a3">a1</label>
</div>
<div class="settings">
<input type="radio" id="b1" name="b" value="1" style="display: none;" />
<label for="b1">a1</label>
<input type="radio" id="b2" name="b" value="2" style="display: none;" />
<label for="b2">a1</label>
<input type="radio" id="b3" name="b" value="3" style="display: none;" />
<label for="b3">a1</label>
</div>
我需要一个jquery监听器来点击一个单选按钮,但是我很困惑,因为没有点击单选按钮,它们被隐藏了。这是点击的标签。我还需要知道点击了哪个按钮。这就像我得到的那样:
$('.settings label').click(function() {
alert("Something was clicked"); // test - not working
// need something to determine what was clicked
updateSettings('a', 'value'); // what was checked, and the value, stored to database via separate function
});
但这不起作用,我不知道如何判断点击了什么(a1,a2 .. b2等)
答案 0 :(得分:4)
将其更改为:
$('.settings label').click(function() {
console.log('Value of Radion: '.concat($(this).prev().val(), 'Name of radio: ', $(this).prev().attr('name')));
});
&#13;
input[type=radio] {
display: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="settings">
<input type="radio" id="a1" name="a1" value="1" />
<label for="a1">a1</label>
<input type="radio" id="a2" name="a2" value="2" />
<label for="a2">a1</label>
<input type="radio" id="a3" name="a3" value="3" />
<label for="a3">a1</label>
</div>
<div class="settings">
<input type="radio" id="b1" name="b1" value="1" />
<label for="b1">a1</label>
<input type="radio" id="b2" name="b2" value="2" />
<label for="b2">a1</label>
<input type="radio" id="b3" name="b3" value="3" />
<label for="b3">a1</label>
</div>
&#13;
答案 1 :(得分:3)
使用查询 .attr()
试试这个,
$(function(){
$('.settings label').click(function() {
updateSettings($(this).attr('for'), $('#'+$(this).attr('for')).val());
});
});
答案 2 :(得分:2)
答案 3 :(得分:1)
尝试:
$('.settings label').click(function () {
var iName = $('#'+$(this).attr('for')).attr('name');
var iVal = $('#'+$(this).attr('for')).val()
// need something to determine what was clicked
updateSettings(iName,iVal); // what was checked, and the value, stored to database via separate function
});
答案 4 :(得分:1)
您需要将其置于doc ready中:
$(function(){
$('.settings label').click(function() {
var cliked = this.getAttribute('for'); // get you the for attr for clicked label
alert(cliked + ' clicked.');
updateSettings(cliked, $(':radio[id="'+ cliked +'"]').val());
// cliked is what is clicked and other param is checked radio value
});
});