我是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>
答案 0 :(得分:0)
您需要使用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>
答案 1 :(得分:-1)
以下是点击时更新div的演示代码。
document.getElementById('first').addEventListener("click", function(){
//Text could be replaced by ajax call
document.getElementById('first').innerHTML = 'Something new';
});
&#13;
<div id='first'>Something 1</div>
<div>Something 2</div>
&#13;