2010-10-24 16 views
0

$ j = 1; ?> var t =''; var options =「」;我如何追加或預先使用jquery這個動態行到表中

</script> 
     <?php 
     foreach ($this->data['DEFAULTS'] as $rec){ 
      foreach ($rec as $key=>$val){ 
     ?> 
     <script type="text/javascript"> 
     var cntr = "<?php echo $j;?>"; 
     var reference_value = '<?php echo $val["GETVAL"];?>'; 
     var sel = '<select name="code[]">'+options+'</select>'; 
     var txt = '<input type="text" class="TextBox" name="referencevalue[]" valign="top" value="'+ reference_value +'">';     
      t += '<tr id ='+cntr+'><td>'+cntr+'</td><td valign="top">'+sel+'</td><td valign="top" ailgn="center">'+txt+'</td></tr>';       
      </script> 

     <?php 
     $j++;    
       } 
      } 
     ?> 
     <script type="text/javascript"> 
     alert("MYTABLE "+t); 
     $("#ref").append(t); 
     </script> 

     when i say alert(t) iam getting the entire table structure and the data but iam not able to add it to the table 
    .Here is the Table Structure where i have to add 
       <table width="100%" cellspacing="2" cellpadding="2" align="left"> 
       <tbody><tr> 
       <th class="coltextleft"> 
       <span style="font-size: 14px; font-weight: bold;" id="id_refTbl"> 
       <img id="IMG1" height="15" width="15" align="middle" src="cllpsed.gif"/> </span> 
       </th> 
       </tr> 
       <tr><td> 
       <div id="ref" style="display:none"> 
       <table id="ref" width="100%" class="formTable"> 
       <tr> 
        <td>&nbsp;</td> 
        <td> Code</td> 
        <td> Value</td> 
        <td>&nbsp;</td> 
       </tr> 
       <tr><td>I need to add the result of alert(t) with inthis rows</td></tr></table> 

回答

1

首先,那種元的問題:你爲什麼要這麼做?爲什麼不直接通過PHP在頁面中呈現標記,而是爲客戶端呈現<script>元素來完成相同的任務?


直接回答:需要被包裹在一個document.ready處理你的代碼,因爲與id="ref"元素尚未在DOM中,當你執行:

$("#ref").append(t); 

所以它沒有找到尚未存在的元素。它包裝在一個ready處理,像這樣的:它執行

$(function() { 
    $("#ref").append(t); 
}); 

這種方式後,DOM完全加載/蓄勢待發,而#ref選擇找到你後<table>


爲了使這項工作雖然,你還需要刪除<div id="ref" style="display:none">id,因爲標識必須是唯一的。

+0

感謝它解決了。所以我的問題是。我如何得到選擇從我的PHP函數返回的選項 var my_option_selected =「<?php echo json_encode(StuClass :: getopt($ val [」CDE「]] ,$ OPT));?>「; var sel =''; – Someone 2010-10-24 19:12:12

+0

@Someone - 需要在你的'

+0

我有兩行已經用於表格「ref」我必須在兩行之後添加動態行 – Someone 2010-10-24 19:45:57

1

如果變量t是整個表格標記,那麼是的,如果你試圖將它附加到表格中,這可能不起作用。你可能會想噸至是:

var t = '<tr><td>foo</td></tr>' 

在這一點上,你應該能夠:

$("table#ref").append(t) 

的jQuery#附加添加標記到目標元素的兒童結束。

+0

'.prepend()'也可以,它將元素作爲第一個孩子而不是最後一個。他的't'也只是*行。最後,*從不*使用任何#id選擇器,如果你可以避免它,它* *慢得多。 – 2010-10-24 18:53:59

+0

選擇器建議的好處 - 我認爲使用基於元素名稱的選擇器仍然非常快,因爲它基於本地DOM查詢方法。如果可能的話,你確實希望避免基於類名的查詢,或者至少縮小搜索範圍。 – Collin 2010-10-24 19:01:59

+0

這取決於,因爲jQuery 1.4.3大多數情況下使用'querySelectorAll()',如果可用的話,但'#id'是一個甚至沒有去Sizzle的特殊情況,它是一個直接的'document.getElementById(「id」 )'快捷鍵,所以* *比*任何其他選擇器都快* – 2010-10-24 19:06:40

相關問題