在不使用jquery的表中追加新行后设置焦点

时间:2015-02-16 06:34:34

标签: javascript jquery

我已经写了这段代码

function addNew(){
$('#container').append(
'<tr class="records" height="1em">'
+'<td align="center"><input  id="" name="UraiF" ></td></tr>');
$('table#myTable tr:last td:first input').focus();}

HTML代码

<table id="#myTable">
<thead>
<th style="width:5%;" align="center">No.</th>
</thead>
<tbody id="container">
<tr class="records">
<td><input  id="" name="UraiF" ></td>
<tr>
</table>

这个按钮甚至点击:

<button onclick="addNew()"></button>

但什么都没发生,任何人都可以帮助我

2 个答案:

答案 0 :(得分:3)

我认为你需要在container内找到tbody的输入,同时确保这个tbody的id在整个DOM中必须是唯一的。请看下面的代码

function addNew(){
  $('#container').append(
  '<tr class="records" height="1em">'
   +'<td align="center"><input  id="" name="UraiF" ></td></tr>');
  $('tbody#container tr:last td:first input').focus();
}

答案 1 :(得分:0)

首先检查是否存在任何控制台错误 - 它们通常是描述正在发生的事情并且你可以修复它们,

其次 - 这可能会被添加,你只是不知道它,因为你的行中唯一的输入标记是无效的。试着修理它

function addNew(){
   $('#container').append(
   '<tr class="records" height="1em">'
   +'<td align="center"><input  id="" name="UraiF" type="text" /></td></tr>');
   $('table#myTable tr:last td:first input').focus();
}

同样 - 为了简化事情,我只想写:

$('#container input').last();

另一件事,这很糟糕而且令人困惑:

<table id="#myTable"> // - 把#out从这里拿出来