2013-03-01 45 views
1

我有一個問題,即一旦我的頁面被渲染,焦點不會被設置在動態創建的表格/輸入的第一個輸入元素上。無法獲得.focus處理動態創建的輸入元素

在.JSP我有以下幾點:

<script type="text/javascript"> 
    $(document).ready(function(){ 

    if(_page != "one") { 
     buildTable(shipQty); 
     $('#shipItems[0].barCode').focus(); 
    } 

</script> 

有一個包含的.js其中包含buildTable功能

function buildTable(shipQty) 
{ 
    var _tbl = $('<table>').attr({ 
    id : 'barCodeTable', 
    border : '1' 
    }); 

    _tbl.append($('<tr>').append($('<td>').text('Box BarCode'),$('<td>').text('INBOUND Tracking Number'))); 

    for (var _index = 0; _index < shipQty; _index++) 
    { 
    var _inputBarCode = $('<input>').attr({ 
      class : 'form-med', 
      type : 'text', 
      name : 'shipItems[' + _index + '].barCode', 
      id : 'shipItems[' + _index + '].barCode', 
      maxlength: '8' 
     }).change(_barCodeChange); 

    var _shippingTrackingCode = $('<input>').attr({ 
     class : 'form-med', 
     type : 'text', 
     name : 'shipItems[' + _index + '].shipCompanyBarCode', 
     id : 'shipItems[' + _index + '].shipCompanyBarCode' 
    }).change(_trackingNumberChange); 

    _tbl.append($('<tr>').append($('<td>').append(_inputBarCode)).append($('<td>').append(_shippingTrackingCode))); 

    } 

    $('#tableWrap').append(_tbl); 
} 

我曾在幾個不同的解決方案here採取一看,herehere和其他人在stackoverflow但無濟於事。

我不明白這裏的問題。

回答

4

它與動態代碼無關。問題是你的jQuery選擇器不符合你想要的。你的代碼正在尋找一個屬性爲零的元素。

您需要轉義.[]

$('#shipItems\\[0\\]\\.barCode').focus(); 

運行例如: http://jsfiddle.net/NC4uz/


jQuery Selector docs

使用任何元字符(如!"#$%&'()*+,./:;<=>[email protected][\]^ {|}〜) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with ID =「富.bar「`,可以使用選擇符$(」#foo \ .bar「)。W3C CSS規範包含有關有效CSS選擇器的完整規則集。 Mathias Bynens在標識符的CSS字符轉義序列上輸入。

+0

我必須做以下$(「#shipItems \\ [0 \\] \\。barCode」)。focus();得到我的例子作品 – boyd4715 2013-03-01 14:22:25