SweetAlert2 检测单选按钮 select

SweetAlert2 detect radio button select

我正在使用 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 给收音机输入 '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 的工作原理而无法正常工作?

您必须通过委托事件绑定整个文档来绑定事件。

$(document).on("click",".swal2-container input[name='swal2-radio']", function() {
    var id = $('input[name=swal2-radio]:checked').val();
    console.log('id: ' + id);
});

勾选Fiddle Link