【问题标题】:Reload an element with javascript使用 javascript 重新加载元素
【发布时间】:2017-11-16 16:04:08
【问题描述】:

我对 JavaScript 非常陌生,我正在尝试在单击该 div 时仅使用 Javascript 重新加载一个元素(一个 div)..

我找到了 location.reload() 函数,但这会重新加载整个页面。这对我不起作用,因为在单击按钮时,我想显示单击该 div 所花费的时间。

我不会放代码,因为它会使问题过于复杂。我基本上只是想知道是否有像 location.reload() 这样的函数可以用来定位特定元素(div),以便重新加载。

更新:这里是代码:

<h1>Test your Reactions!</h1>
<p>click on the boxes and circles as quickly as you can</p>

<p id="timeNeeded"></p>

<div id="circle"></div>

        <script type="text/javascript">

        //defining variables
var myColors = ["green", "blue", "red", "purple", "orange", "black"];
var myShape = ["50px", "inherit"];

var startTime, endTime, timeDiff;
var randColor = myColors[Math.floor(Math.random() * myColors.length)];
var randShape = myShape[Math.floor(Math.random() * myShape.length)];


// defining function: Setting the color and shape of the box
function setStyle () {

    var circle = document.getElementById("circle");
     circle.style.backgroundColor = randColor;
     circle.style.borderRadius = randShape;
}

// defining function: Set Start time
 function start() {
  startTime = new Date();
}

// defining end function and time difference
function end() {
  endTime = new Date();
}

// starting time measure
start();


//exectute style
setStyle();

// Clicking the button
document.getElementById("circle").onclick = function () {

// reloads the page
// location.reload();


end();
var timeDiff = endTime - startTime;

}
  document.getElementById("timeNeeded").innerHTML = "Your reaction: " + timeDiff

        </script>
    </body>
</html>

【问题讨论】:

  • 分享您的代码。 div是如何创建的?你需要重新加载什么?
  • 你不能“重新加载”一个 div,但是你可以按需重新填充它的内容,所以你可以创建一个函数来为你“重新加载”
  • 部分重载需要使用ajax
  • 这是一个使用 ajax 更新元素以响应点击事件的示例:w3schools.com/xml/tryit.asp?filename=tryxml_httprequest
  • 搜索和学习ajaxjquery 提供了一个简单的实现来处理 ajax。

标签: javascript html css reload


【解决方案1】:

您需要使用AJAX重新加载页面的部分常量而不重新加载。

<!DOCTYPE html>
<html>
<body>

<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</div>

<script>
function loadXMLDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "xmlhttp_info.txt", true);
  xhttp.send();
}
</script>

</body>
</html>

或者,如果您只需要更改 div 内容,请使用以下代码

<!DOCTYPE html>
<html>
<body>

<div id="demo">
Text 1
</div>
<button type="button" onclick="loadDiv()">Change Content</button>

<script>
function loadDiv() {
  document.getElementById("demo").innerHTML = "Text 1 "  + Math.random(); ;
}
</script>

</body>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-22
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 2020-08-16
    • 2013-09-10
    • 1970-01-01
    • 2014-08-25
    相关资源
    最近更新 更多