当javascript onclick时显示div中的文本

时间:2013-05-27 01:29:22

标签: javascript

我有多个按钮,每个按钮都有相关文字,当用户点击按钮时,文字应根据按钮改变,文字应显示在DIV中。

我正在使用if elseif在每个按钮的文本之间进行选择,现在我无法通过该函数将文本传递给div onclick()。

<html>  
   <head>  
      function display (selected) {  
         if (decision == firstbox)  {  
            display = "the text related to first box should be displayed";  
         }  else if (decision == secondbox)  {  
            display = "Text related to 2nd box.";  
         }  else  {  
            display ="blank";  
         } 
   </head>  
   <body>  
      <input type="button" id="firstbox" value= "firstbox" onclick="display(firstbox)" /><br>    
      <input type="button" id="secondbox" value= "secondbox" onclick="display(firstbox)" /><br>
   </body>
</html>

3 个答案:

答案 0 :(得分:1)

您的代码中的纯JavaScript:

function display (selected)
  {
  if (selected == 'firstbox')
    {
    texttoshow = "the text related to first box should be displayed";
    }
  else if (selected == 'secondbox')
    {
    texttoshow = "Text related to 2nd box.";
    }
  document.getElementById("thetext").innerHTML = texttoshow;
  }

和html:

<body>
  <div id = "thetext"></div>
  <button onclick = "display(firstbox)">Firstbox</button>
  <button onclick = "display(secondbox)">Secondbox</button>
</body>

值得一提的是,jQuery(一个javascript框架):

$("#buttonclicked").
  click(function(){
    $("#yourdiv").
      html("Your text");
    });

答案 1 :(得分:0)

这应该做你想要的事情

<button type="button" id="button-test">Text that will apear on div</button>
<div id="content">
</div>
    <script type="text/javascript">
     $(document).ready(function(){
     $('#button-test').click(function(){
$('#content').text($(this).text());
    });
     });
    </script>

http://remysharp.com/2007/04/12/jquerys-this-demystified/

http://api.jquery.com/text/

答案 2 :(得分:0)

在这里,我将为您提供一个示例。其中一个使用 div 而另一个没有,一个使用链接,另一个使用需要点击的按钮。

<!DOCTYPE html>
<html>
<body>

<h2>Displaying text when clicked</h2>

<button type="button"
onclick="document.getElementById('demo').innerHTML = 'These are the steps to get your PIN number: Bla bla bla'">
PIN button:</button>

<p id="demo"></p>


</br></br></br>

<a onclick="showText('text1')" href="javascript:void(0);">PIN link:</a>

<script language="JavaScript">
   function showText(id)
    {
        document.getElementById(id).style.display = "block";
    }
</script>

<div id="text1" style="display:none;">These are the steps to get your PIN number: Bla bla bla</div>

</body>
</html>