【发布时间】:2013-04-01 19:39:04
【问题描述】:
我正在使用来自 AJAX 调用的数据动态创建一个表。我正在使用“选择/下拉框”.on('change') 函数将值发送到我的 PHP。表格显示后,我想将焦点设置在表格上动态创建的搜索框上。
问题似乎在于,由于表格需要几秒钟才能可见,所以 .focus() 命令会在表格可见之前触发。我希望在创建表函数完成后触发 .focus() 命令。
Javascript/Jquery 代码:
$('#t6F3Box1').on('change', function()
{
var $newTable ='<table id="tempEmployerTbl" class="studentTables"><thead><tr>';
var $searchStr=new RegExp("ID");
var $tableContainerDiv="#t6F3TableCont";
var $rowFlag=0;
var $responseDataValue=[]
var $employerState=$('#t6F3Box1').val();
var $getTableDataPhp="../application/employer.php";
var $data=[];
$('#t6F3ErrDiv').text('');
$('#t6F3TableCont, #t6F3HLine2, #t6F3HLine2').show();
$data += "&employerState=" + encodeURIComponent($employerState);
$.ajax({
type: 'POST',
async: false,
url: $getTableDataPhp,
cache: false,
datatype: 'json',
data: $data,
success: function($responseData)
{
//Loop through the responsdata returned in a JSON Array
//dynamically create the Employer drop down box
if (!$responseData.authenticationError)
{
//Create the header for the Employer Table
$.each($responseData, function($key, $value)
{
if($rowFlag==0)
{
$responseDataValue=$responseData[$key];
$.each($responseDataValue, function($keys, $values)
{
if ($searchStr.test($keys))
{
$newTable += '<th class="tableDataHide">' + $keys + '</th>';
}
else
{
$newTable += '<th class="tableDataShow">' + $keys + '</th>'
}
});
$rowFlag=1;
}
});
$newTable +='</tr></thead><tbody>';
//Create the body for the Employer Table
$.each($responseData, function($key, $value)
{
$newTable += '<tr>'
$responseDataValue=$responseData[$key];
$.each($responseDataValue, function($keys, $values)
{
if ($searchStr.test($keys))
{
$newTable += '<td class="tableDataHide">' + $values + '</td>';
}
else
{
if($values==null)
{
$values="";
}
$newTable += '<td class="tableDataShow">' + $values + '</td>'
}
});
$newTable +='</tr>';
});
$newTable +='</tbody></table>';
$($tableContainerDiv).html($newTable);
$("#tempEmployerTbl").dataTable();
$('#tblSearchBox').focus();
}
}
});
【问题讨论】:
-
我看不到
.focus()事件在您的代码中设置的位置。除此之外,您还有两种可能的选择:(1) 在附加表后附加事件处理程序或 (2) 委托事件,以便在动态添加元素时,jQuery 为您附加事件处理程序。有关后者的更多信息,请查看.delegate()或.on()的 api 文档,具体取决于您运行的 jQuery 版本。 -
抱歉,我已将 .focus 命令重新插入到代码不起作用的位置。在此处插入 .focus() 时,它会在表格有机会加载到 HTML 页面上之前完成焦点。我尝试将函数绑定到 this 以及使用事件侦听器到 on change 函数,但无济于事。
-
它不会出错,但你应该修复 $data。它被初始化为一个数组,然后在其上使用了一个字符串 concat。
-
@MatthewWitt 这就是代表团发挥作用的地方。使用
.on()或.delegate()创建事件处理程序。当元素中的内容发生变化时,jQuery 会在适当的时候自动为您附加事件。来自.delegate()的 jQuery api 文档:根据一组特定的根元素,为现在或将来匹配选择器的所有元素附加一个或多个事件的处理程序。跨度> -
@war10ck 根据 API 文档:从 jQuery 1.7 开始,.delegate() 已被 .on() 方法取代。然而,对于早期版本,它仍然是使用事件委托的最有效方法。有关事件绑定和委托的更多信息在 .on() 方法中。一般来说,这些是这两种方法的等效模板。
标签: javascript jquery ajax datatables