javascript - 将代码从 jquery 重写为 javascript

标签 javascript jquery onbeforeunload

在我的小部件中我有以下代码:

$(document).ready(function() {
    $('a[rel!=ext]').click(function() { window.onbeforeunload = null; });
    $('form').submit(function() { window.onbeforeunload = null; });
});

我已将此代码放在许多网页中。我的问题是,并非所有网页都运行 jQuery,因此我需要一个 JavaScript 解决方案。

这在 JavaScript 代码中会是什么样子?

更新:

function showWidget(www){

  var content = '<iframe src="'+www+'" style="border:0px #FFFFFF none; position: fixed;left: 0px;width: 300px; height:100%; top: 30%;z-index: 9999999;" name="myiFrame" scrolling="yes" frameborder="0" marginheight="0px" marginwidth="0px" height="100%" width="100%"></iframe><a style="display:none;" href="http://bedbids.com" rel="ext">BedBids</a>';

var newNode = document.createElement("DIV");  
newNode.innerHTML = content;
document.body.appendChild(newNode); 


window.onbeforeunload = function() {
        return "You're leaving the site.";
    };
   window.onload = function() {
   [].slice.call(document.querySelectorAll('a[rel!="ext"]')).forEach(function(a) {
       a.onclick = function() {
           window.onbeforeunload = null;
       };
   });
   [].slice.call(document.getElementsByTagName('form')).forEach(function(form) {
       form.onsubmit = function() {
           window.onbeforeunload = null;
       };
   });
};

}

最佳答案

这样的事情应该有效:

window.onload = function() {
   [].slice.call(document.querySelectorAll('a[rel!=ext]')).forEach(function(a) {
       a.onclick = function() {
           window.onbeforeunload = null;
       };
   });
   [].slice.call(document.getElementsByTagName('form')).forEach(function(form) {
       form.onsubmit = function() {
           window.onbeforeunload = null;
       };
   });
};

关于javascript - 将代码从 jquery 重写为 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37071053/

相关文章:

javascript - 如何在 jQuery 中使用附加动画?

javascript - Microsoft Edge 中的 beforeunload 未触发

javascript - 如何将数组复制到从某个单元格开始的列的每个单元格,而不是复制到一行的每个单元格?

javascript - 更改触发路由器事件的导航

javascript - 检测 Javascript 何时表现不佳

javascript - 通过拖放将 KnockoutJS 与 JQuery 结合使用

javascript - 在 Ajax 调用中传递 Json.Net 对象

javascript - Intersection Observer 不与 sibling 一起工作

javascript - 使用 window.confirm 而不是 onbeforeunload