如何将JavaScript确认为HTML5按钮操作?

发布于 2025-02-11 21:21:10 字数 641 浏览 2 评论 0原文

我有以下代码:

if(changedStatus()){
    var mAns = confirm("You have changed your status. This will alter your estate plan and may cause you to lose some data. Are you sure that you want to do this?");
    if(!mAns) return false; 
}

这与默认的JS确认弹出窗口非常有用,但是我想用HTML5按钮实现相同的操作:

<div id="cres_statusmssg">
  <p>Changing your status will alter your estate plan and may cause you to lose some data. Do you want to proceed?</p>
   <button id="cres_yes">Yes</button>
   <button id="cres_cancel">Cancel</button>

我已经将单击事件应用于两个按钮,但是我无法让它们上班。有什么想法吗?

I have the following code:

if(changedStatus()){
    var mAns = confirm("You have changed your status. This will alter your estate plan and may cause you to lose some data. Are you sure that you want to do this?");
    if(!mAns) return false; 
}

This works great with the default JS confirm pop-up, but I would like to implement the same action with HTML5 buttons instead:

<div id="cres_statusmssg">
  <p>Changing your status will alter your estate plan and may cause you to lose some data. Do you want to proceed?</p>
   <button id="cres_yes">Yes</button>
   <button id="cres_cancel">Cancel</button>

I have applied click events to both buttons, but I can't get them to work. Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

神妖 2025-02-18 21:21:10

您需要了解如何为异步而写作,因为没有其他方法可以实现您想做的事情。内置的确认(提示>提示> ,arter> arter et)有效地暂停JS

执行 - up,您没有那么奢侈。您需要使用回调来实现一个工作解决方案,

我建议使用诺言 - 无论如何,这只是荣耀的回调,还可以将能够与async /等待 - 这具有使代码 LOW 更像您使用的代码的优点,如果您没有做太多的异步编码

function statusmssgDialog() {
  const dlg = document.getElementById('cres_statusmssg');
  dlg.showModal();
  return new Promise((resolve, reject) => {
    const clk = function(e) {
      resolve(this.dataset.value === 'true');
      dlg.close();
    };
    dlg.querySelectorAll('button').forEach(btn =>
      btn.addEventListener('click', clk, { once: true})
    );
  });
}



// usage - it's easier if the function where you
//    call statusmssgDialog is `async`
//    but you can also use Promise.then/.catch of course
//
async function fn() {
  if( true /*changedStatus()*/){
    const mAns = await statusmssgDialog();
    console.log(`user action is ${mAns}`);
    if(!mAns) return mAns;
  }
  console.log('doing more things here when yes is clicked or chengedStatus is false?');
}



// asynchrony is like a virus, 
// anything that calls an asynchronous function and needs the result
// needs to be written to account for asynchrony
// here, I use .then/.catch instead of async/await
// because await isn't an option at the top-level of code
// unless it's the top-level of a module script in modern browsers 
fn().then(r => {
  if (r === false) {
    console.log('cancel was clicked');
    return;
  }
  console.log('yes was clicked');
});
.modal-dialog {
  border-radius: 9px;
  box-shadow: 0 0 1em rgb(127 127 127 / 0.8);
  width: 30rem;
  max-width: 90%;
}

.modal-dialog::backdrop {
  background: rgb(0 0 0 / 0.4);
  backdrop-filter: blur(1px);
}
body {
  background-color: hsl(240 100% 95%);
}
<dialog id="cres_statusmssg" class="modal-dialog">
  <div>
    <p>Changing your status will alter your estate plan and may cause you to lose some data. Do you want to proceed?</p>
    <button id="cres_yes" data-value="true">Yes</button>
    <button id="cres_cancel" data-value="false">Cancel</button>
  </div>
</dialog>

<div>
  <p>Dummy page text</p>
<div>

在以上,对话框承诺总是可以解决的,但是还有其他选择,如果按下取消

function statusmssgDialog() {
  const dlg = document.getElementById('cres_statusmssg');
  dlg.showModal();
  return new Promise((resolve, reject) => {
    const clk = function(e) {
      dlg.close();
      if (this.dataset.value !== 'true') {
        return reject('cancel pressed');
      }
      resolve('yes pressed');
    };
    dlg.querySelectorAll('button').forEach(btn =>
      btn.addEventListener('click', clk, { once: true})
    );
  });
}

async function fn() {
  if( true /*changedStatus()*/) {
    try {
      const mAns = await statusmssgDialog();
      console.log(`yes pressed`);
    } catch(e) {
      console.log('cancel was pressed');
      throw e; // pass the cancel "error" to the caller
    }
  }
  console.log('doing more things here when yes is clicked or chengedStatus is false?');
}

fn().then(r => {
  console.log('yes was clicked');
}).catch(e => {
  console.log(`user action was ${e}`);
});
.modal-dialog {
  border-radius: 9px;
  box-shadow: 0 0 1em rgb(127 127 127 / 0.8);
  width: 30rem;
  max-width: 90%;
}

.modal-dialog::backdrop {
  background: rgb(0 0 0 / 0.4);
  backdrop-filter: blur(1px);
}
body {
  background-color: hsl(240 100% 95%);
}
<dialog id="cres_statusmssg" class="modal-dialog">
  <div>
    <p>Changing your status will alter your estate plan and may cause you to lose some data. Do you want to proceed?</p>
    <button id="cres_yes" data-value="true">Yes</button>
    <button id="cres_cancel" data-value="false">Cancel</button>
  </div>
</dialog>

<div>
  <p>Dummy page text</p>
<div>

You'll need to understand how to write for asynchrony, since there is no other way to achieve what you want to do. The built-in confirm (and prompt, alert etc) effectively pause JS execution until the user has interacted with the pop-up

Writing nicer pop-ups, you don't have that luxury. You'll need to use callbacks to achieve a working solution

I'd recommend using Promises - which are just glorified callbacks anyway, with the added advantage of being able to be used with async/await - this has the advantage of making the code look more like the code you're used to if you haven't done much asynchronous coding

function statusmssgDialog() {
  const dlg = document.getElementById('cres_statusmssg');
  dlg.showModal();
  return new Promise((resolve, reject) => {
    const clk = function(e) {
      resolve(this.dataset.value === 'true');
      dlg.close();
    };
    dlg.querySelectorAll('button').forEach(btn =>
      btn.addEventListener('click', clk, { once: true})
    );
  });
}



// usage - it's easier if the function where you
//    call statusmssgDialog is `async`
//    but you can also use Promise.then/.catch of course
//
async function fn() {
  if( true /*changedStatus()*/){
    const mAns = await statusmssgDialog();
    console.log(`user action is ${mAns}`);
    if(!mAns) return mAns;
  }
  console.log('doing more things here when yes is clicked or chengedStatus is false?');
}



// asynchrony is like a virus, 
// anything that calls an asynchronous function and needs the result
// needs to be written to account for asynchrony
// here, I use .then/.catch instead of async/await
// because await isn't an option at the top-level of code
// unless it's the top-level of a module script in modern browsers 
fn().then(r => {
  if (r === false) {
    console.log('cancel was clicked');
    return;
  }
  console.log('yes was clicked');
});
.modal-dialog {
  border-radius: 9px;
  box-shadow: 0 0 1em rgb(127 127 127 / 0.8);
  width: 30rem;
  max-width: 90%;
}

.modal-dialog::backdrop {
  background: rgb(0 0 0 / 0.4);
  backdrop-filter: blur(1px);
}
body {
  background-color: hsl(240 100% 95%);
}
<dialog id="cres_statusmssg" class="modal-dialog">
  <div>
    <p>Changing your status will alter your estate plan and may cause you to lose some data. Do you want to proceed?</p>
    <button id="cres_yes" data-value="true">Yes</button>
    <button id="cres_cancel" data-value="false">Cancel</button>
  </div>
</dialog>

<div>
  <p>Dummy page text</p>
<div>

In the above, the dialog promise always resolves, but there is an alternative, to reject if cancel is pressed

function statusmssgDialog() {
  const dlg = document.getElementById('cres_statusmssg');
  dlg.showModal();
  return new Promise((resolve, reject) => {
    const clk = function(e) {
      dlg.close();
      if (this.dataset.value !== 'true') {
        return reject('cancel pressed');
      }
      resolve('yes pressed');
    };
    dlg.querySelectorAll('button').forEach(btn =>
      btn.addEventListener('click', clk, { once: true})
    );
  });
}

async function fn() {
  if( true /*changedStatus()*/) {
    try {
      const mAns = await statusmssgDialog();
      console.log(`yes pressed`);
    } catch(e) {
      console.log('cancel was pressed');
      throw e; // pass the cancel "error" to the caller
    }
  }
  console.log('doing more things here when yes is clicked or chengedStatus is false?');
}

fn().then(r => {
  console.log('yes was clicked');
}).catch(e => {
  console.log(`user action was ${e}`);
});
.modal-dialog {
  border-radius: 9px;
  box-shadow: 0 0 1em rgb(127 127 127 / 0.8);
  width: 30rem;
  max-width: 90%;
}

.modal-dialog::backdrop {
  background: rgb(0 0 0 / 0.4);
  backdrop-filter: blur(1px);
}
body {
  background-color: hsl(240 100% 95%);
}
<dialog id="cres_statusmssg" class="modal-dialog">
  <div>
    <p>Changing your status will alter your estate plan and may cause you to lose some data. Do you want to proceed?</p>
    <button id="cres_yes" data-value="true">Yes</button>
    <button id="cres_cancel" data-value="false">Cancel</button>
  </div>
</dialog>

<div>
  <p>Dummy page text</p>
<div>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文