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 に答える