2013-05-14 83 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