2013-05-14 77 views
1

我已閱讀了關於此主題的每篇文章,並嘗試了許多「解決方案」,但它似乎並沒有爲我工作。追加後的訪問元素

$(function() { 

    var options = { 
     source: [ 
      "ActionScript", 
      "AppleScript", 
      "Asp", 
      "BASIC", 
      "C", 
      "C++", 
      "Clojure", 
      ], 
     minLength: 2 
    }; 

    $('#btn_addline').on ("click", function() { 

     // get existing line number and increment by one 
     var linenum = parseInt ($('#numlines').val()) + 1; 

     // update hidden numlines field with new value 
     $('#numlines').val(linenum); 

     // define new field names 
     var line_field = 'report['+linenum+'][line]'; 
     var notes_field = 'report['+linenum+'][notes]'; 
     var contact_field = 'report['+linenum+'][contact]'; 

     var newLine = $('<tr> \ 
      <td><input name="'+line_field+'" id="'+line_field+'" type="text" size="2" maxlength="2" class="form" value="'+linenum+'" readonly="readonly" /></td> \ 
      <td><input name="'+notes_field+'" id="'+notes_field+'" type="text" size="96" maxlength="256" class="form" /></td> \ 
      <td><input name="'+contact_field+'" id="'+contact_field+'" onFocus="attach_autocomplete()" type="text" size="32" maxlength="32" class="form" value="test123" /></td> \ 
      </tr>'); 

     // append new line to table 
     //$('#report_items').append(newLine); 

     $('#report_items').append(newLine) 
      .hide() 
      .fadeIn('Normal', function() { 
       $(this).find('#'+contact_field).val('test'); 
       //alert ($(this).find('#'+contact_field).val()); 
       alert (contact_field); 
       alert ($('#'+contact_field).val()); 
      }); 

     //$('#'+contact_field).autocomplete(options); 

    }); 
}); 

新的HTML被正確添加,但是我沒有做任何事情可以訪問這些元素。我在整個網站嘗試了各種建議,現在我很沮喪,希望得到一些幫助。

第三次提醒 - alert ($('#'+contact_field).val()); - 返回「未定義」。

要清楚,我已經徹底地瀏覽了類似問題的列表,但還沒有找到解決方案。這很可能是我錯過了一些明顯的東西,或者我不太理解追加元素和它對DOM的影響之間的關係,但是無論如何,我真的可以在這裏使用一隻手。

乾杯。

+2

向我們展示你的HTML,或使用http://jsfiddle.net/ – 2013-05-14 07:35:05

+0

將添加HTML。現在建立jsfiddle。 – 2013-05-14 07:37:12

+1

我建議你從你的id中取代'''''並使用下劃線'_',就像''report_'+ linenum +'__line_'' – Catalin 2013-05-14 07:42:24

回答

2

問題是您的選擇器中有特殊字符。你需要逃生者以兩個反斜槓\\:!

使用任何元字符(如 「#$%&「()的* +,/ :; < =>? @ [] ^`{|}〜)作爲名稱的文字部分,它必須用兩個反斜槓轉義:例如,一個帶有 id =「foo.bar」的元素可以使用選擇器$ ( 「#foo \的.bar」)。

Check out the documentation

+0

謝謝。當我在選擇器中使用變量時,我的印象並不適用。我嘗試了你的建議,但是我得到了完全相同的結果。我正試圖在jsfiddle上解決它。 – 2013-05-14 07:43:56

+0

您將無法更改變量,否則最終會在元素本身顯示反斜槓,並且選擇器不會選擇任何內容。你可以創建另一個,或直接寫入選擇器 – billyonecan 2013-05-14 07:51:21

+0

我已經更新了你的小提琴向你展示我的意思:http://jsfiddle.net/deifwud/xBRk2/1/ – billyonecan 2013-05-14 07:52:51