日期:2014-05-16  浏览次数:20306 次

onload前的执行方法
当我们静态页面在呈现body内容前,我要先执行一个函数来判断是否符合查看内容条件,只有符合查看条件后,才会显示body内容要怎么写才好。我用body onload=""
它是内容已经显示出来了,换其他事件又找不出什么事件才好。
HTML code

<!--以下代码纯手工编写。仅提供问题表述,大家帮看看-->
<html>
<head>
<title>
页面标题
</title>
<script type="text/javascript">
function checkRole()
{
var key= document.getElementById("txtValue").value;

if(key=="3")
{
  if(confirm('当前页面要求您登录,点击确定进行登录,取消返回首页'))
{
  document.location.href="/user/userlogin.shtml";
}
else
{
  document.location.href="/index.shtml";
}
}
}
</script>

</head>
<body>
页面内容
<input type="text" id="txtValue" value="3"/>
</body>
</html>



================
问题是:如何在页面呈现body前执行checkRole();
如果说有办法在页面呈现body前执行checkRole();
那又如何解决var key= document.getElementById("txtValue").value;这个取值问题。好困惑。

------解决方案--------------------
不明白楼主楼实现什么效果, 用JS控制权限作用不大, 如果客户禁用JS怎么办?

为什么把权限写在<body>里的<input里, 而且不直接写在<script>里,如:
<script>
...
function checkRole(k)
{
var key= k;
...
}
checkRole(3);

</script>

按楼主的方法可以把checkRole函数放在要取值的<input下方即可
HTML code
<html>
<head>
<title>
页面标题
</title>
<script type="text/javascript">
function checkRole()
{
var key= document.getElementById("txtValue").value;

if(key=="3")
{
  if(confirm('当前页面要求您登录,点击确定进行登录,取消返回首页'))
{
  document.location.href="/user/userlogin.shtml";
}
else
{
  document.location.href="/index.shtml";
}
}
}
</script>

</head>
<body>
页面内容
<input type="text" id="txtValue" value="3"/>
<script>
 checkRole();
</script>
中华人民共和国
</body>
</html>

------解决方案--------------------
那就打破一下常规.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script language="javascript" type="text/javascript">
function check() {
if (document.getElementById('v1').value == '1') {
alert('...');
} else {
alert('???');
window.opener = null;
window.close();
}
}
</script>
</head>

<body>
<input type="hidden" id="v1" name="v1" value="3" />
<script language="javascript" type="text/javascript">
check()
</script>
ddd
ddd
ddd
</body>
</html>


不过人家禁用了JS脚本就完了.
------解决方案--------------------
HTML code


<html>
<head>
<title>
页面标题
</title>
<script type="text/javascript">
function checkRole()
{
var key= document.getElementById("txtValue").value;

if(key=="3")
{
  if(confirm('当前页面要求您登录,点击确定进行登录,取消返回首页'))
{
  document.location.href="/user/userlogin.shtml";
}
else
{
  document.location.href="/index.shtml";
}
}
}
</script>

</head>
<body>
页面内容
<input type="text" id="txtValue" value="3"/>
<script>
 checkRole();
</script>
中华人民共和国
</body>
</html>

------解决方案--------------------
首先要说明的是,这种通过JS来控制权限的方法很不严密,查看页面源码就可以看到内容。

以下是按楼主要求的解决方案,其实很简单:先将<body>之间的内容用display:none隐藏,判断值后再决定是否显示。以下代码测试通过:
HTML code