SweetAlert2检测单选按钮选择

问题描述:

我使用SweetAlert2 JavaScript库来显示弹出窗口。 SweetAlert2是SweetAlert的一个分支,它不再被维护。 SweetAlert2允许我这样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无线电”名称添加单选按钮收音机输入,这样

<input id="swal2-radio-1" type="radio" name="swal2-radio" value="3"> 

所以我尽量听swal2无线电的任何点击像这样:

$("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

+0

太感谢你了,我绝不会用我自己想通了这一点 –