1

我有多个按钮,每个按钮都有相关文本,当用户单击按钮时,文本应根据按钮更改,文本应显示在 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>
4

3 回答 3

2

来自您的代码的纯 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");
    });
于 2013-05-27T01:33:52.100 回答
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/

于 2013-05-27T01:39:02.337 回答
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> 
于 2017-07-14T20:12:25.583 回答