我正在学习编写 JavaScript 代码。在此脚本中,我希望链接不转到其指定位置,而是更改其前面段落中的文本。我创建了一个函数来实现它onclick
,但该函数无法返回 false。
<html>
<head>
<title>Javascript Test #6</title>
<script type="text/javascript">
document.getElementById("links").onclick=writeData();
function writeData()
{
document.getElementById("para").innerHTML="Changed Paragraph Content";
return false;
}
</script>
</head>
<body>
<p id="para">Unchanged Paragraph Content</p>
<br/>
<a id="links" href="javascript-return.html"> Click here to change the paragraph content </a>
</body>
</html>
最佳答案
document.getElementById("links").onclick=writeData;
不要使用括号。它们迫使你的函数进行评估。但您想要分配该功能。
编辑:
当然,您需要在文档加载后分配您的功能。现在的情况是,执行赋值时不会有 id links
的元素。基本上,只需将脚本 block 放在 links
元素下方即可。
<html>
<head>
<title>Javascript Test #6</title>
</head>
<body>
<p id="para">Unchanged Paragraph Content</p>
<br/>
<a id="links" href="javascript-return.html"> Click here to change the paragraph content </a>
<script type="text/javascript">
document.getElementById("links").onclick=writeData;
function writeData()
{
document.getElementById("para").innerHTML="Changed Paragraph Content";
return false;
}
</script>
</body>
</html>
编辑(使用window.onload):
<html>
<head>
<title>Javascript Test #6</title>
<script type="text/javascript">
window.onload = function() {
document.getElementById("links").onclick=writeData;
}
function writeData()
{
document.getElementById("para").innerHTML="Changed Paragraph Content";
return false;
}
</script>
</head>
<body>
<p id="para">Unchanged Paragraph Content</p>
<br/>
<a id="links" href="javascript-return.html"> Click here to change the paragraph content </a>
</body>
</html>
关于javascript - 如何使链接在点击时更改段落内容?返回 false 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8179324/