离开页面javascript / jquery

时间:2014-03-17 02:47:07

标签: javascript jquery

我的问题是这篇文章https://stackoverflow.com/questions/22438863/javascript-jquery-for-before-leaving-the-page?noredirect=1#comment34138272_22438863的延续,它是一个新功能。

我正在寻找以下功能:

在stackoverflow中,如果您输入一些答案,如果您尝试关闭该选项卡,它将要求确认消息..

以下是我的Html部分:

<form id="demo">
 <input type="text" id="name" name=""/>
 <input type="email" id="emails" name=""/>
 <input type="number" id="ph" name=""/>
 <select name="" id="sample">
  <option>Select</option>  
  <option value="1">Chennai</option>
  <option value="2">Hyderabad</option>
 </select>
</form>

如果用户输入了某些东西,他点击了徽标就会导航它要求确认消息..自然正确???甚至stackoerflow都有这个功能..我试过这段代码但没有工作

var changesMade = false;

function onDataChanged() {
 changesMade = true;
}

$('input:text, textarea, select').change(onDataChanged);
$('input:checkbox, input:radio').click(onDataChanged);

$("#homeicon").click(function() {
 if (changesMade) {
    return 'Changes have been made. Are you sure you want to leave the page?';
    location.href = "home.html";
 } else {
    return null;
 }
});

1 个答案:

答案 0 :(得分:4)

您正在jQuery中寻找onbeforeunloadbeforeunload

检查here以及使用该字词搜索其他地方。