gpt4 book ai didi

javascript - SweetAlert2 从自定义 HTML 中的输入中获取值

转载 作者:太空宇宙 更新时间:2023-11-04 15:54:53 24 4
gpt4 key购买 nike

问题

我正在使用 SweetAlert2 ,打开其中包含自定义 HTML 的警报,其中显示了几个输入框。我想使用 SweetAlert2 中的普通确认/取消按钮将这些输入的值发送到套接字。

问题

如何使用普通的 SweetAlert2 按钮获取这些输入的值?请不要建议使用普通输入或 HTML 按钮,因为这是一种解决方法,我不希望这样。

环境

我使用 jQuery、SweetAlert2 和一些不相关的库,例如 Vue.js 和 Socket.io 等。

代码

function addUser() {
swal({
html: `
<div class="field">
Email:
<p class="control has-icons-left">
<input class="input" type="email" placeholder="Email">
<span class="icon is-small is-left">
<i class="mdi mdi-email"></i>
</span>
</p>
</div>
<div class="field">
Name:
<p class="control has-icons-left">
<input class="input" type="text" placeholder="Name">
<span class="icon is-small is-left">
<i class="mdi mdi-account"></i>
</span>
</p>
</div>
<div class="field">
Password:
<p class="control has-icons-left">
<input class="input" type="text" placeholder="Password">
<span class="icon is-small is-left">
<i class="mdi mdi-key"></i>
</span>
</p>
</div>
<div class="field">
Level:
<p class="control has-icons-left">
<input class="input" type="text" placeholder="Level">
<span class="icon is-small is-left">
<i class="mdi mdi-arrow-up"></i>
</span>
</p>
</div>
`,
confirmButtonText: 'Confirm',
cancelButtonText: 'Cancel',
confirmButtonClass: 'button is-success has-right-spacing',
cancelButtonClass: 'button is-danger',
buttonsStyling: false,
showCancelButton: true
})
}

最佳答案

由于您使用的是自定义 HTML 输入,因此库 API 中的常规设置不足以实现您的目标。我建议您使用他们的 API 函数中的 preConfirm 从您的输入中获取值,如下所示:

function addUser() {
swal({
html: `...`,
confirmButtonText: 'Confirm',
// ...
showCancelButton: true,
preConfirm: function() {
return new Promise((resolve, reject) => {
// get your inputs using their placeholder or maybe add IDs to them
resolve({
Email: $('input[placeholder="Email"]').val(),
Name: $('input[placeholder="Name"]').val(),
Password: $('input[placeholder="Password"]').val(),
Level: $('input[placeholder="Level"]').val()
});

// maybe also reject() on some condition
});
}
}).then((data) => {
// your input data object will be usable from here
console.log(data);
});
}

关于javascript - SweetAlert2 从自定义 HTML 中的输入中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46591494/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com