在我的小部件中我有以下代码:
$(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/