我在w3school找到了一个关于数据属性的示例程序,我想在段落表单中自定义显示而不是在警告框中显示它,并在单击的列表下显示它。
我该怎么做?
<!DOCTYPE html>
<html>
<head>
<script>
function showDetails(animal) {
var animalType = animal.getAttribute("data-animal-type");
alert("The " + animal.innerHTML + " is a " + animalType + ".");
}
</script>
</head>
<body>
<h1>Species</h1>
<p>Click on a species to see what type it is:</p>
<ul>
<li onclick="showDetails(this)" id="owl" data-animal-type="bird">Owl</li>
<!--show here-->
<li onclick="showDetails(this)" id="salmon" data-animal-type="fish">Salmon</li>
<!--show here-->
<li onclick="showDetails(this)" id="tarantula" data-animal-type="spider">Tarantula</li>
<!--show here-->
</ul>
</body>
</html>
答案 0 :(得分:1)
创建一个指定为输出元素的<p>
(或者,如果您使用语义,则可以使用<output>
)。然后,按其ID选择它,并将其innerHTML
设置为正确的输出:
// Select the <p> tag by its id attribute
var outputElement = document.getElementById("output");
function showDetails(animal) {
var animalType = animal.getAttribute("data-animal-type");
// Instead of an alert()
outputElement.innerHTML = ("The " + animal.innerHTML + " is a " + animalType + ".");
}
<h1>Species</h1>
<p>Click on a species to see what type it is:</p>
<ul>
<li onclick="showDetails(this)" id="owl" data-animal-type="bird">Owl</li>
<!--show here-->
<li onclick="showDetails(this)" id="salmon" data-animal-type="fish">Salmon</li>
<!--show here-->
<li onclick="showDetails(this)" id="tarantula" data-animal-type="spider">Tarantula</li>
<!--show here-->
</ul>
<!-- Output element with the id of "output" -->
<p id="output"></p>
答案 1 :(得分:1)
尝试将.insertAdjacentHTML
与参数afterend
一起使用,将<p></p>
中的字符串替换为alert()
中的字符串,并在animal.onclick = null
附近添加showDetails
最多拨打showDetails
一次
<!DOCTYPE html>
<html>
<head>
<script>
function showDetails(animal) {
var animalType = animal.getAttribute("data-animal-type");
animal
.insertAdjacentHTML("afterend"
, "<p>The " + animal.innerHTML + " is a " + animalType + ".</p>");
animal.onclick = null;
}
</script>
</head>
<body>
<h1>Species</h1>
<p>Click on a species to see what type it is:</p>
<ul>
<li onclick="showDetails(this)" id="owl" data-animal-type="bird">Owl</li>
<!--show here-->
<li onclick="showDetails(this)" id="salmon" data-animal-type="fish">Salmon</li>
<!--show here-->
<li onclick="showDetails(this)" id="tarantula" data-animal-type="spider">Tarantula</li>
<!--show here-->
</ul>
</body>
</html>
&#13;
答案 2 :(得分:0)
首先,将<script>
标记放在</body>
的末尾,然后添加以下代码:
<script>
var paragraph = document.createElement('p'); // create new <p> element
document.body.appendChild(paragraph); // add it to your <body> tag
function showDetails(animal) {
var animalType = animal.getAttribute("data-animal-type");
paragraph.innerHTML = "The " + animal.innerHTML + " is a " + animalType + ".";
}