我正在使用 SweetAlert2 javascript 库来显示弹出窗口。 SweetAlert2 是 SweetAlert 的一个分支,不再维护。 SweetAlert2 允许我添加这样的单选按钮
// inputOptions can be an object or Promise
var inputOptions = new Promise(function(resolve) {
resolve({
'#ff0000': 'Red',
'#00ff00': 'Green',
'#0000ff': 'Blue'
});
});
swal({
title: 'Select color',
input: 'radio',
inputOptions: inputOptions,
inputValidator: function(result) {
return new Promise(function(resolve, reject) {
if (result) {
resolve();
} else {
reject('You need to select something!');
}
});
}
}).then(function(result) {
swal({
type: 'success',
html: 'You selected: ' + result
});
})
SweetAlert2 为 radio 输入指定“swal2-radio”名称,如下所示
<input id="swal2-radio-1" type="radio" name="swal2-radio" value="3">
所以我尝试监听 swal2-radio 的任何点击,如下所示:
$("input[name='swal2-radio']").on("click", function() {
var id = $('input[name=swal2-radio]:checked').val();
console.log('id: ' + id);
});
它应该打印到控制台,以便我知道它有效。
这是我到目前为止的代码: https://jsfiddle.net/ayx0fkz3/
我做错了什么,还是因为 SweetAlert2 的工作方式而不起作用?
最佳答案
您必须通过委托(delegate)事件与整个文档绑定(bind)来绑定(bind)事件。
$(document).on("click",".swal2-container input[name='swal2-radio']", function() {
var id = $('input[name=swal2-radio]:checked').val();
console.log('id: ' + id);
});
关于javascript - SweetAlert2 检测单选按钮选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39641241/