如何使用jquery从动态生成的表单元素中获取元素Id? [英] How to get element Id from dynamically generated form elements with jquery?
问题描述
为了尝试这个概念,我正在进行一个非常简单的测试。
To try the concept, I'm doing a very simple test.
我从一开始就看到一个带有一些文本输入的表单。
当我点击某个字段时,我想捕获它的Id,并在输入文本中添加一个值。
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');
});
});
这适用于初始字段,但它停止使用ajax调用添加的字段。
This works great with the initial fields, but it stops working with the fields added using ajax calls.
诀窍是,用户可以点击任何字段,直到他们点击我才知道哪个字段。
My Ids看起来像这样:
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
([n]部分也用于将表单中的字段作为元素排序按经验,教育技能等分组......
(the [n] part is also used to order the fields in the form as elements are grouped by experience, education skills etc...
我该如何实现?
推荐答案
一个简单的改变:
$(document).ready(function() {
$('input').live("focus", function() {
var currentId = $(this).attr('id');
$("#"+currentId).val('blah');
});
});
.focus
仅绑定到调用时存在的元素。 .live()
将函数绑定到事件所有现有元素,以及稍后添加到DOM中的任何元素。
.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从动态生成的表单元素中获取元素Id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!