我在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>发布于 2016-01-27 02:56:18
尝试在参数.insertAdjacentHTML中使用afterend,将<p></p>中的字符串替换为在alert()中放置字符串,在showDetails结束时添加animal.onclick = null最多一次调用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>
发布于 2016-01-27 02:50:25
创建一个指定为输出元素的<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>
发布于 2016-01-27 02:54:04
首先,将<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 + ".";
}https://stackoverflow.com/questions/35027875
复制相似问题