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

问题描述 投票:1回答:1

我需要一些帮助来理解我的代码的行为。假设有两个页面,您可以通过单击第一页中的链接打开第二页,返回第一页通过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>
javascript html
1个回答
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()是通过不执行默认单击行为来阻止更改URL的行。

© www.soinside.com 2019 - 2024. All rights reserved.