2013-08-19 2 views
-2

Я хотел бы знать, как получить значение на основе события click. У меня есть код для получения текстового значения.Как получить значение из определенного ТД на основе события click

document.getElementById(elem).innerText; 

где elem - идентификатор конкретного. Я хотел бы присвоить это определенной переменной и использовать ее как строку для запроса из базы данных. Но проблема в том, что я не могу заставить это быть сохраненным в переменной.

window.hold = document.getElementById(elem).innerText; 

Я сделал это, чтобы присвоить его переменной. Но я должен назначить это переменной PHP, и эта часть дает мне ошибку. Пожалуйста, помогите мне.

Поэтому в основном то, что я хочу это:

<td id='1'>one</td> 
<td id='2'>two</td> 
<td id='3'>three</td> 

так, если я нажимаю на один. Я должен записывать данные внутри td и назначать ему переменную. Спасибо заранее.

<?php 

echo "<div id='one'>"; 
echo "<div align='center' id='title' style='font-size:32px;font-family: 'trebuchet MS', sans-serif;'>Meter Health</div>"; 
echo "<table class='table' width='100%' cellpadding='0' cellspacing='5' style='font-size:32px;'>"; 
$id = 0; 
for ($i = 0; $i < 10; $i++) { 
    $id++; 
    echo "<tr>"; 
    for ($a = 0; $a < 10; $a++) { 
     $c = rand(2000, 9000); 
     $b = rand(10, 100); 
     if ($b <= 40) { 
      $color = 'red'; 
     } elseif ($b <= 60) { 
      $color = 'orange'; 
     } else { 
      $color = 'green'; 
     } 
     echo "<td id=$id; title='$b%'; bgcolor='$color'; 
        onmouseover='ChangeColor(this, true);' 
         onmouseout='ChangeColor(this, false);'    
        align ='center' 
        onclick='view(); print($b);' 


      >$c</td>"; 
    } 
    echo "</tr>"; 
} 
echo "</table>"; 
echo "</div>"; 

?> 

PHP будет генерировать таблицу, и я хочу функцию, чтобы получить значение а присваиваемое переменной как строки, основанной на события мыши.

<html> 
    <head> 
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" /> 
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> 
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> 
    <!--[if lt IE 9]><script language="javascript" type="text/javascript" src="dist/excanvas.js"></script><![endif]--> 

<script language="javascript" type="text/javascript" src="js/jquery.min.js"></script> 
<script language="javascript" type="text/javascript" src="js/jquery.jqplot.min.js"></script> 
<link rel="stylesheet" type="text/css" href="js/jquery.jqplot.css" /> 
<script language="javascript" type="text/javascript" src="js/jqplot.barRenderer.min.js"></script> 
<script language="javascript" type="text/javascript" src="js/jqplot.categoryAxisRenderer.min.js"></script> 
<script language="javascript" type="text/javascript" src="js/jqplot.pointLabels.min.js"></script> 


    <script> 

     function ChangeColor(tableRow, highLight) { 
      if(highLight) { 
       tableRow.style.backgroundColor = 'yellow'; 
      } else { 
       tableRow.style.backgroundColor = defaultStatus; 
      } 
     } 

     $(function() { 
      $(document).tooltip(); 
     }); 


     function view() { 
      document.getElementById("one").style.visibility = "visible"; 
      if(document.getElementById("one").style.display == "none") { 
       document.getElementById("one").style.display = ""; 
       document.getElementById("two").style.display = "none"; 
      } else { 
       document.getElementById("one").style.display = "none"; 
       document.getElementById("two").style.display = ""; 
       $.jqplot.config.enablePlugins = true; 
       var s1 = [2, 6, 7]; 
       var ticks = ['IP', 'BILLING', 'LOAD SURVEY']; 

       plot1 = $.jqplot('chart1', [s1], { 
        // Only animate if we're not using excanvas (not in IE 7 or IE 8).. 
        animate: !$.jqplot.use_excanvas, 
        seriesDefaults: { 
         renderer: $.jqplot.BarRenderer, 
         pointLabels: { 
          show: true 
         } 
        }, 
        axes: { 
         xaxis: { 
          renderer: $.jqplot.CategoryAxisRenderer, 
          ticks: ticks 
         } 
        }, 
        highlighter: { 
         show: true 
        } 
       }); 

       $('#chart1').bind('jqplotDataClick', 
        function (ev, seriesIndex, pointIndex, data) { 
         $('#info1').html('series: ' + seriesIndex + ', point: ' + pointIndex + ', data: ' + data); 
        } 
       ); 
      } 
     } 


    </script> 
    <script>  
     $(document).ready(function(){ 

     }); 
    </script> 
    <style> 
     table td 
{ 
    border:1px solid #ccc; 
    padding:4px; 

    width: 45px; 
    height: 45px; 
    display: inline-block; 
    overflow: auto; 
} 


     td{ 

      -moz-border-radius-topleft: 75px; 
-moz-border-radius-topright:0px; 
-moz-border-radius-bottomleft:0px; 
-moz-border-radius-bottomright:75px; 
-webkit-border-top-left-radius:75px; 
-webkit-border-top-right-radius:0px; 
-webkit-border-bottom-left-radius:0px; 
-webkit-border-bottom-right-radius:75px; 
border-top-left-radius:75px; 
border-top-right-radius:0px; 
border-bottom-left-radius:0px; 
border-bottom-right-radius:75px 

     } 

    </style> 

    </head> 

    <body> 

     <?php 
     echo "<div id='one'>"; 
     echo "<div align='center' id='title' style='font-size:32px;font-family: 'trebuchet MS', sans-serif;'>Meter Health</div>"; 
     echo "<table class='table' width='100%' cellpadding='0' cellspacing='5' style='font-size:32px;'>"; 
      $id=0; 
     for($i=0;$i<10;$i++) 
     { $id++; 

      echo "<tr>"; 
      for($a=0;$a<10;$a++){ 
       $c=rand(2000,9000); 
       $b=rand(10,100); 

       if($b<=40){ 
        $color='red'; 
       } 
       elseif($b<=60){ 
        $color='orange'; 
       } 
       else{ 
        $color='green'; 
       } 



      echo "<td id=$id; title='$b%'; bgcolor='$color'; 
        onmouseover='ChangeColor(this, true);' 
         onmouseout='ChangeColor(this, false);'    
        align ='center' 
        onclick='view(); print($id);' 


      >$c</td>"; 


      } 
      echo "</tr>"; 



     } 
     echo"</table>"; 
     echo "</div>"; 




     ?> 
     <div id='two' style='display:none;'> 
     <div id="chart1" style="height:400px;width:700px; margin-left: 9em; margin-top: 3em; margin-bottom: 4em; text-align: center;"></div> 
     <div><button onclick='view();'>Back</button></div> 
     </div> 
     <script> 
     function print(elem) { 
      // window.hold=document.getElementById(elem).innerHTML; 
      window.hold = document.getElementById(elem).innerText; 
      document.write(window.hold); 
      console.log(hold); 
      // console.log(elem); 
      // document.getElementById("two").innerHTML=elem; 
     } 
     </script> 
    </body> 
</html> 
+0

опубликуйте свой код, с которым у вас возникла проблема, то, что вы опубликовали, не имеет значения. – DevZer0

+0

'Но я должен назначить это переменной PHP. Что? –

+0

см. Значение td может быть записано с использованием .innerhtml или .innertexty. Но когда я устанавливаю это в переменную и печатаю ее, это дает мне ошибку sayin undefined. Я хотел бы знать, как это сделать. – user2409375

ответ

0
var hold = document.getElementById(elem).innerText; 
+0

Я назначил его var, но это не сделает его глобальным. Поэтому я использовал его с window.variable, но проблема в том, что он покажет мне undefined, когда я его печатаю. – user2409375

+0

Если он показывает вам undefined, это значит, что код document.get ... был вызван до того, как dom закончил загрузку. Попробуйте это window.onload = function() {// здесь код – Haben

+0

Uncaught TypeError: Не удается прочитать свойство 'innerText' из null am, получившего эту ошибку – user2409375

0

Создайте объект, например:

GLOBAL = { "variable" : "" } 

затем для события щелчка:

tdClicked = function(){ 
     GLOBAL.variable = document.getElementByID(elem).innerText; 
    } 
0

Просто измените print($id) на print(this) и

function print(elem) { 
    var hold = elem.innerText; 
    console.log(hold); 
}