html5数据属性显示在文本中

时间:2016-01-27 02:41:04

标签: javascript html5

我在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>

3 个答案:

答案 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一次

&#13;
&#13;
<!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;
&#13;
&#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 + ".";
}