更改类之前触发事件

时间:2019-03-14 02:13:10

标签: javascript jquery html css

有许多按钮和链接可以让我退出一页。在将该页面留给其他用户之前,我想向用户询问一些内容,然后退出该页面。

在我们的应用中,“离开此页面”就像从<canvas class="show"></canvas><canvas class=""></canvas>,并显示另一个画布。其他人已经做到了。我的目标是检测是否删除了class="show"

我已阅读thisthis等。我还很初级,不了解它们的真正含义,或者只是不知道如何在我的问题中实现它。

请帮助,下面是更具体的示例列表:

$('body').on('class_change_event', () => {
    swal({
        title: "Are you sure?",
        text: 'If you close without saving, your changes will discarded.',
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "Save"
    })
    // After the user choose, do the original jobs
})
div.demo { 
    border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

<div class="demo">
    <canvas class="load show"></canvas>
    <canvas class="load"></canvas>
    <canvas class="load"></canvas>
</div>

<a href="https://www.google.com">go to Google</a>
<a href="index.html">back to index</a>
<input type="button" value="Clear canvas" />

注意
  • 即使用户单击buttona,也会导致class="show"发生更改。
  • 我不确定将事件附加到$('body')上是否正确

2 个答案:

答案 0 :(得分:1)

如果要阻止用户离开页面,则要使用beforeunload事件。这将导致浏览器提示用户是否真的要离开该页面。但是,如果您使用的是SPA,则需要绑定到框架的路由以在其更改路由时显示提示。

window.addEventListener("beforeunload", function(e) { ... });

https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

答案 1 :(得分:1)

好的。我接到你了。我想这就是您所需要的。我们创建看起来像的观察者  用于目标元素的类更改。在 .load 类的所有元素中。也可以查看脚本中的注释。

let views = [...document.querySelectorAll(".load")];
views.forEach(view => {

  // create an observer instance that will look for class changes
  var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      // we only need to detect class changes
      if (mutation.attributeName !== 'class') {
        return false;
      }
      // exact node which classList has been changed
      let el = mutation.target
      if (el.classList.contains("show")) {
        confirmLeave();
      }
    });
  });

  // configuration of the observer. We need to detect "class" attribute changes 
  var config = {
    attributes: true
  };

  // pass in the target node, as well as the observer options
  observer.observe(view, config);
})

// Let's test our observer
setTimeout(() => {
  document.querySelector('.load').classList.add('show')
}, 2000)

function confirmLeave() {
  // this string is just to check and show you can remove it later and use your script below
  document.querySelector('.text').textContent = 'Element got "show" class!';
  /*swal({
    title: "Are you sure?",
    text: 'If you close without saving, your changes will discarded.',
    type: "warning",
    showCancelButton: true,
    confirmButtonText: "Save"
  })*/
}
.load {
  width: 20px;
  height: 20px;
  border: 1px solid #333;
}

.load.show {
  background-color: red;
}

.text {
  margin-top: 10px;
}
<div class="load"></div>

<div class="text"></div>