我有一个经典的table/thead/tbody
结构,我在tbody的末尾添加了一行。该行仅包含一个 input
元素。该代码可以在 Firefox 3.6 中运行,但不能在 Chrome v5 或 IE8 中运行。我正在使用 jQuery 1.4.2。
不起作用:
$("#"+ AJAX_ID).parent().find('tr:last > td:nth-child(2) > input').focus();
有效:
$("#"+ AJAX_ID).parent().find('tr:last > td:nth-child(2) > input').css('background-color', 'red');
即使在输入上设置 ID,并使用 document.getElementBuId('id').focus()
也不起作用。
*** 编辑 ***
该网站非常复杂(模板/静态 html 和动态 html 的混合),但是表格 看起来像这样(在 chrome 中渲染 html,通过 tidy 进行布局):http://pastebin.com/PHqxAEVm
*** 编辑 2 ***
即使从 ajax 回调调用 $("#lectures").find("input:last").focus();
也不会执行任何操作.. $("#lectures").find("input:last").css('background-color', 'red');
虽然变为一红色,但焦点转到地址栏。
这是从选择器返回的对象的转储: http://pastebin.com/Jdw1TZXf
*** 编辑 3 ***
以下是构建表的 JavaScript 代码:http://pastebin.com/cbCfi0UY
页面加载时,oContainer
是 $("#lectures")
,而在 ajax 调用之后它是 $("#"+ AJAX_ID).parent()
code>,应该指向表的 tbody
*** 编辑 4 ***
难题...这是完整的lectures.js
文件:http://pastebin.com/Jkg0DZqa
batisses
和 compteurs
是通过模板加载的 json 对象。用户选择一个 batisse
,然后选择一个 compteur
,然后按下一个调用 buildAjout()
的按钮,在本例中调用 buildElectric($ (“#lectures”),compteur);
。一旦用户填满该行,就会调用 onBlurLecture(tr_parent)
,数据通过 AJAX 发送到服务器,并在 ajax 之后调用 callback_compteurs_lecture_add(AJAX_ID)
函数通话完成。函数 SendCommand
是一个使用 jQuery ajax 的自定义函数。
第一个输入行(和焦点)的创建有效,但在 ajax 回调中创建的输入行无效。
*** 编辑 5 ***
完整呈现的页面如下所示:http://pastebin.com/UfBYcjX3
我缩短了 batisses
变量。 (完整)页面没有 JavaScript 错误。
在 Chrome 的 JavaScript 控制台中,我无法聚焦输入。
*** 编辑 6 ***
此问题中 SendCommand
的函数名称错误。已修复。
找到的解决方案: .focus() doesn't work on an input while orher attributes works
最佳答案
您的目标 ID 是什么?因为如果我用 $('table')
替换 $("#"+ AJAX_ID)
,它就可以工作 -> demo (至少在 Chrome 中)
如果我将函数包装在 $(document).ready(function(){...})
中,它可以在 IE 中工作 -> demo
我仍在寻找问题所在,但到目前为止我对您的代码有一些评论。
我还没有对此进行测试,但我创建了一个 jQuery 对象,然后在其中附加另一个对象,最终由于函数调用的数量而花费了大量时间。我发现构建一个字符串并仅使用一个附加更容易。这个例子很容易阅读:
var table = '\ <table style="width: 100%">\ <thead>\ <tr>\ <th>Numéro</th>\ <th>litre</th>\ <th style='width: 100px;'>Status</th>\ </tr>'; // append more to the string table += '<tbody>.....</tbody></table>'; $('body').append(table);
我找到了这段代码,我只是想向您展示您可以缩短它:
$("#no_batisse").css('display', 'none'); $("#lectures").html(""); $("#lectures").css('display', '');
缩短为:
$("#no_batisse").hide(); $("#lectures").empty().hide();
您可以尝试添加一个可处理动态添加内容的
live
函数,而不是在添加每一行后调用此函数:$(oLigne).find("input").blur(function() { onBlurLecture(oLigne); });
尝试在初始化脚本时运行它(仅一次)
$('#lecture').find('input').live('blur', function(){ onBlurLecture( $(this).closest('tr') ); })
我会继续寻找!
关于javascript - .focus() 不适用于输入,而其他属性则有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2760901/