2012-07-18 57 views
0

我有一個父頁面需要由iframe調用的函數,然後這個函數更新iframe中的表單值。我可以調用的功能正常,但表格值更新不起作用從iframe調用父功能,然後更新iframe的形式值

我設置了一個警報,看父函數是否可以看到輸入值,但返回undefined,所以我假設我沒有正確訪問ID的

這裏是我的代碼試圖自動初始化今天的領域日期分成三個文本框

主要js函數

window.autoPartialDateBox = function(htmlID) { 
if (!jQuery('#'+htmlID+"_mm").val() && !jQuery('#'+htmlID+"_dd").val() && !jQuery('#'+htmlID+"_yy").val()) { 
      var myDate = new Date();  
      jQuery('#'+htmlID+"_mm").val(myDate.getMonth()+1);      
      jQuery('#'+htmlID+"_dd").val(myDate.getDate()); 
      jQuery('#'+htmlID+"_yy").val(myDate.getFullYear());    
} } 

IFRAME

<script type="text/javascript"> 
    $(function() { 
     // this will populate the partial date box   
      $("#someElement").live("change", function() { 
       if ($(this).val() == 'trigger') { 
       window.top.autoPartialDateBox('partial_date_box'); 
       } 

      }); 

     }); 
    </script> 

Action <select name="someElement" id="someElement" class="valid"> 
    <option value="" selected="">Select an option</option> 
    <option value="trigger">Trigger</option>    
</select> 

Day <input name="stop_dd_2747_mm" type="text" id="stop_dd_2747_mm"> 
Month <input name="stop_dd_2747_dd" type="text" id="stop_dd_2747_dd" > 
Year <input name="stop_dd_2747_yy" type="text" id="stop_dd_2747_yy" > 

回答

0

如果您認爲該問題正在訪問該ID,那可能是因爲您試圖在jQuery選擇器中「構建」該ID。我認爲更好的解決方案是將函數傳遞給父元素,然後橫過節點樹來查找輸入字段。

功能:

window.autoPartialDateBox = function(parentElm) { 

    $nodes = jQuery(parentElm).children('input[type=text]'); 

    if (!$nodes[0].val() && !$nodes[1].val() && !$nodes[2].val()) { 


     var myDate = new Date();  
     $nodes[0].val(myDate.getMonth()+1);      
     $nodes[1].val(myDate.getDate()); 
     $nodes[2].val(myDate.getFullYear());    
    } 
} 

添加一個容器,用於您的輸入字段:

<div id="input_container"> 
    Day <input name="stop_dd_2747_mm" type="text" id="stop_dd_2747_mm"> 
    Month <input name="stop_dd_2747_dd" type="text" id="stop_dd_2747_dd" > 
    Year <input name="stop_dd_2747_yy" type="text" id="stop_dd_2747_yy" > 
</div> 

我沒有測試過,但是是一般的方法我會做到這一點。我不知道如果你嘗試在選擇器中構建一個字符串,jQuery的行爲如何。這似乎不是一個問題,但你永遠不知道。

EDIT聲明jQuery的命名空間 '節點' 出現

+0

相同的錯誤,不能調用的未定義的方法 'VAL'。在函數被包含在文檔中時,在jquery選擇器中構建一個字符串可以正常工作,當它包含在頂部/父項中時失敗,然後嘗試調用 – 2012-07-18 18:18:25

+0

如果錯誤發生在If上,那麼您需要檢查'.val )'爲每個子節點。 '!node [0] .val()'等等。如果錯誤發生在node [0] .val()上,那麼該節點需要用'$'在jQuery名稱空間中聲明。 – ExceptionLimeCat 2012-07-18 18:29:55

+0

我編輯了IF&'節點'聲明。 – ExceptionLimeCat 2012-07-18 18:33:19