我试图写一个简单的网页,其中一个段落中的文本被替换为两个可能的段落之一,这取决于哪个按钮被点击。 当我点击任何一个按钮时都不会发生任何事情。 我试过到处移动代码,但这似乎不起作用。 这是整个文档,经过编辑以保留不必要的细节
null
var mypar = document.getElementById("default");
document.getElementById("one").onclick = "Story1()"
document.getElementById("two").onclick = "Story2()"
function Story1(){
mypar.innerHTML = "long paragraph";
}
function Story2(){
mypar.innerHTML = "long paragraph";
}
body {
background-color: blue;
}
.button{
border-radius: 8px;
display: inline-block;
text-align: center;
background-color: #4CAF50;
padding: 15px 32px;
font-size: 32px;
}
h1 {
text-align: center;
color: yellow;
text-decoration: underline;
text-shadow: 2px 2px;
}
p {
padding-right: 50px;
padding-left:250px;
text-align: justify;
color: white;
font-style: italic;
font-weight: bold;
}
<h1>
<img src="people.jpg" alt= "onetwo" >
<br>
<button class="button" id = "one"> one </button>
<button class="button" id = "two"> two</button>
<br>
Heading </h1>
<p id = "p1">
long paragraph.</p>
<p id ="default">
</p>
<p id = "end">
written here
</p>
null
不要将事件处理程序指定为字符串。 使用函数本身:
document.getElementById("one").onclick = Story1;
或者更好:
document.getElementById("one").addEventListener("click", Story1);
更新得代码段:
null
var mypar = document.getElementById("default");
document.getElementById("one").addEventListener("click", Story1);
document.getElementById("two").addEventListener("click", Story2);
function Story1(){
mypar.innerHTML = "long paragraph 1";
}
function Story2(){
mypar.innerHTML = "long paragraph 2";
}
body {
background-color: blue;
}
.button{
border-radius: 8px;
display: inline-block;
text-align: center;
background-color: #4CAF50;
padding: 15px 32px;
font-size: 32px;
}
h1 {
text-align: center;
color: yellow;
text-decoration: underline;
text-shadow: 2px 2px;
}
p {
padding-right: 50px;
padding-left:250px;
text-align: justify;
color: white;
font-style: italic;
font-weight: bold;
}
<h1>
<img src="people.jpg" alt= "onetwo" >
<br>
<button class="button" id = "one"> one </button>
<button class="button" id = "two"> two</button>
<br>
Heading </h1>
<p id = "p1">
long paragraph.</p>
<p id ="default">
</p>
<p id = "end">
written here
</p>
这里发现了两个问题-
只是为了使两个函数的定义不同,我将Story2函数中要替换的innerHTML设置为-“短段落”,而不是“长段落”。
var mypar = document.getElementById("default");
document.getElementById("one").onclick = Story1;
document.getElementById("two").onclick = Story2;
function Story1 () {
mypar.innerHTML = "long paragraph";
}
function Story2 () {
mypar.innerHTML = "short paragraph";
}
尝试看看这个例子,它可以帮助跳动点击事件:
// Function to change the content of t2
function modifyText() {
const t2 = document.getElementById("t2");
if (t2.firstChild.nodeValue == "three") {
t2.firstChild.nodeValue = "two";
} else {
t2.firstChild.nodeValue = "three";
}
}
// Add event listener to table
const el = document.getElementById("outside");
el.addEventListener("click", modifyText, false);