js阻止页面刷新

JavaScript09

js阻止页面刷新,第1张

网页中用户的表单填写到一半,或者ajax请求发送期间,如果用户刷新浏览器可能会导致数据保存失败。需要阻止页面刷新,这时可以通过监听页面window.onbeforeunload事件函数来处理。

window.onbeforeunload = function(e) {

var dialogText = 'Dialog text here'

e.returnValue = dialogText

return dialogText

}

不过chrome不支持自定义显示文字,固定为

“要重新加载该网站吗?

系统可能不会保存您所做的修改”

而firefox和safari就会正常使用return value里面的文字

参考:

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

<html>

<head>

<meta http-equiv="Content-Type" content="text/htmlcharset=utf-8" />

<title>无标题</title>

<script type="text/javascript">

function sum(obj) {

var z = document.getElementById("z")

var a = document.getElementById("a")

var b = document.getElementById("b")

var c = document.getElementById("c")

all.value=parseInt(z.value)

if(a.value!='')

{

y.value=parseInt(a.value)

h.value=parseInt(z.value)-parseInt(a.value)

}

if(a.value!=''&&b.value!='')

{

y.value=parseInt(b.value)+parseInt(a.value)

h.value=parseInt(z.value)-parseInt(a.value)-parseInt(b.value)

}

if(a.value!=''&&b.value!=''&&c.value!='')

{

y.value=parseInt(b.value)+parseInt(a.value)+parseInt(c.value)

h.value=parseInt(z.value)-parseInt(a.value)-parseInt(b.value)-parseInt(c.value)

}

}

</script>

</head>

<body>

总分:<input type="text" id="z" οnkeyup="sum(this)" />

<input type="text" id="a" οnkeyup="sum(this)" />

<input type="text" id="b" οnkeyup="sum(this)" />

<input type="text" id="c" οnkeyup="sum(this)" />

总分:<input type='text' id='all' style="border:0px solid whitewidth:25px" />

已选:<input type='text' id='y' style="border:0px solid whitewidth:25px" />

还剩:<input type='text' id='h' style="border:0px solid whitewidth:25px" />

</body>

</html>

扩展资料

js实现input的赋值

<input  id="name1"  name="teacherName" type="text"  />

$('#name1').val('值')

document.getElementById('name1').value='值'

document.getElementById('name1').html('值')

document.getElementById('name1').attr('值')

document.getElementById('name1').innerText = '值'

<input class="easyui-textbox"  id="name"  name="teacherName" type="text"  />

$('#name').textbox('setValue','值')

var val = $("#name").textbox('getValue')