onclick在插入一些文本后需要多次点击

时间:2017-12-19 21:12:49

标签: javascript html

我需要一些帮助来理解我的代码的行为。假设有两个页面,您可以通过单击第一页中的链接打开第二页,返回第一页通过onclick =“history.go(-1);”功能,工作正常。但是如果我首先使用getElementById-函数在第二页上的div中插入一些文本,则history.go(-1)函数将停止工作。或者它确实有效,但需要多次点击。

我已经读过它是因为DOM模型被更改了,但我不知道如何更正功能。 下面是两页的示例代码,

感谢您的帮助!

第1页;

<!DOCTYPE html>
<html>
<h2>
Please click the link below to open another page.<br>
From that page you should return back here by clicking Back-1 or Back-2.<br><br>
However, if you first click Read comments link, the Back-2 version does not work
or requires several clicks to work.<br><br>

<a href="details.php">Open details</a>
</h2>
</html>

第2页;

<!DOCTYPE html>
<html>
<head>
    <style>
        ul {
            list-style-type: none;
            margin: 0;
            padding: 0;
            overflow: hidden;
            background-color: #C1BDB0;
        }

        li {
            float: left;
        }

        li a {
            display: inline-block;
            color: black;
            text-align: center;
            padding: 14px 16px;
            text-decoration: none;
        }

        li a:hover {
            background-color: grey;
        }
    </style>

    <script >
        function getComments(){
            document.getElementById("infotxt").innerHTML = "This is a fake response from Ajax";
        }
    </script>
</head>
<body>  

<ul>
  <li><a href="<?php echo $_SERVER['HTTP_REFERER'] ?>">Back-1</a></li>
  <li><a onclick="history.go(-1);" href="#">Back-2</a></li>    
  <li><a onclick='getComments()' class='active' href='#'>Read comments </a></li>
</ul>

<div>
    <span id="infotxt"></span>
    <br><br>
    <h2>
    From this page you should return back to previous page by clicking 
    Back-1 or Back-2.<br><br>
    However, if you first click Read comments -link, the Back-2 version does 
    not work or requires several clicks (one double + one) to work.<br>
    The Back-1 version works in both cases.
    </h2>
</div>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

问题是由点击按钮后添加到网址末尾的#引起的。要解决此问题,您可以更改下面的getComments功能,还可以为导航通话创建其他功能。

function goBack(event){
    event.preventDefault();
    history.go(-1);
}

function getComments(event){
    event.preventDefault();
    document.getElementById("infotxt").innerHTML = "This is a fake response from Ajax";
}

此外,更改标记以传递事件对象,如下所示:

<a href="#" onclick="goBack(event);">Back-2</a>
<a href='#' onclick="getComments(event);" class="active">Read comments</a>

event.preventDefault()是通过不执行默认点击行为来阻止更改网址的行。