2つの答え:
- 使用しないでください
confirm
- 本当に使用したい場合は
confirm
、画像を更新した後、confirm
1.使用しないでくださいconfirm
最善の方法は、まったく使用confirm
しないことです。これは時代遅れであり、ページへの変更が表示されるかどうかという点で、ブラウザによって動作が少し異なることがわかりました。
代わりに、非同期で動作する350,124個の「ダイアログ」ライブラリ(jQuery UIには優れたライブラリがありますが、多くあります)を使用するので、ページの変更を確実に確認できます。ループは非同期関数になりますが、慣れればそれほど難しいことではなく、ユーザーエクスペリエンスの面で大きなメリットがあります。
function chooseImage(arr, completionCallback) {
var i = 0, imgElement = document.images['id'];
ask();
function ask() {
imgElement.src = arr[i];
showDialog(gotAnswer); // the nature of "show dialog" will depend on which one you use
}
function gotAnswer() {
if (userSaidYes) { // Again, depends on the library you're using
completionCallback(i); // Tell the calling code which one they picked
}
else {
// Is there another?
++i;
if (i >= arr.length) {
// No, tell the user
/* left as exercise */
// Tell calling code none was chosen
completionCallback(-1); // Using -1 as a flag for none
}
else {
// Yes, ask about it
ask();
}
}
}
}
2.使用するconfirm
が、譲歩する
問題はconfirm
、ブラウザがユーザーに質問をしている間、物事がひどく停止することです。確認ウィンドウがアクティブな間は、ページに加えた変更が表示されない場合があります(これまで見てきたように)。
本当に使用したい場合confirm
でも、それを行うことができます。最初にブラウザに戻って、ページの変更を表示する時間を確保してください。ただし、画像のダウンロードに時間がかかる場合は、これが保証されない場合があることに注意してください。
function chooseImage(arr, completionCallback) {
var i = 0, imgElement = document.images['id'];
showAndHandOff();
function showAndHandOff() {
imgElement.src = arr[i];
setTimeout(ask, 0);
}
function ask() {
if (confirm('do you want to see more?')) {
++i;
if (i >= arr.length) {
alert("Sorry, there aren't any more.");
completionCallback(-1);
}
else {
showAndHandOff();
}
}
else {
completionCallback(i);
}
}
}