将代码从jquery重写为javascript

Rewrite code from jquery to javascript

本文关键字:javascript 重写 jquery 代码      更新时间:2023-09-26

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

$(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;
       };
   });
};