如何使用jquery从动态生成的表单元素中获取元素Id?
为了尝试这个概念,我正在做一个非常简单的测试。
我得到了一个表格,其中从一开始就显示了一些文本输入。 当我单击某个字段时,我想捕获其 Id,并向输入文本添加一个值。
$(document).ready(function() {
$('input').focus(function() {
var currentId = $(this).attr('id');
$("#"+currentId).val('blah');
});
});
这对于初始字段效果很好,但对于使用 ajax 调用添加的字段则停止工作。
诀窍是,用户可以单击任何字段,但在他们单击之前我不知道是哪个字段。 我的 ID 如下所示:
experience0-CompanyName //(original one)
experience[n]-CompanyName
([n] 部分还用于对表单中的字段进行排序,因为元素按经验、教育技能等进行分组......
我怎样才能实现这一点?
To try the concept, I'm doing a very simple test.
I got a form with some text input showing up from the start.
When I click on a field, I want to capture its Id, and add a value to the input text.
$(document).ready(function() {
$('input').focus(function() {
var currentId = $(this).attr('id');
$("#"+currentId).val('blah');
});
});
This works great with the initial fields, but it stops working with the fields added using ajax calls.
The trick is, users are able to click on any field and I don't know which until they click.
My Ids looks like this:
experience0-CompanyName //(original one)
experience[n]-CompanyName
(the [n] part is also used to order the fields in the form as elements are grouped by experience, education skills etc...
how can I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一个简单的更改:
.focus
仅绑定到调用时存在的元素。.live()
将函数绑定到所有现有元素以及以后添加到 DOM 的任何元素的事件。A simple change:
.focus
only binds to elements that exist at the time it's called..live()
binds a function to an event for all existing elements, and any that are added to the DOM later.以前的答案已经不再合适。他们依赖于 jQuery.live,但现已弃用。在 jQuery 1.11 中,调用 jQuery.live 会产生错误。当前的首选解决方案是使用 jQuery.on 。上面的 jQuery.live 代码的实现如下。第二个参数当前设置为“:input”,可以替换为符合您需要的选择器。
The previous answers are no longer appropriate. They rely on jQuery.live, which is now deprecated. In jQuery 1.11, a call to jQuery.live produces an error. The current preferred solution is to use jQuery.on . The implementation of the jQuery.live code, above, would be as follows. The second parameter, currently set to ":input", can be replaced by a selector that conforms to your needs.
它可以更简单(不需要获取 id 并通过它进行搜索):
It can be simpler (no need to get id and search by it):
我相信您正在使用
$("").focus()
。这适用于已加载的文档,不适用于添加的新标签。尝试使用 $("").live("focus",);
另外请查看 jquery 网站。他们得到了非常好的文档和示例。对于实时查看http://api.jquery.com/live/
I belive you are using
$("<someid>").focus(<function>)
. This works on document already loaded and not on new tags added.Try using $("<someid>").live("focus", <function>);
Also do have a look at jquery website. They got quite nice documentation with examples. For live check this out http://api.jquery.com/live/