在 .on 选择器中使用通配符将 jquery 绑定到动态生成的字段
Bind jquery to dynamically generated fields using wildcards in .on selector
我有一个动态生成的表单,它根据用户输入呈现字段。我无法将事件直接绑定到动态生成的字段,因为在首次呈现 DOM 时它们不存在。但是,我可以使用 jquery 的“.on”方法通过像 document.This 这样的父元素绑定事件,因为“.on”接受 selector 到 select子元素"
.on( events [, selector ] [, data ], handler )
在我的测试中,我可以传入静态 selector 并像这样成功绑定事件。
$(document).on('click','#id_task_size_edit',function(){
// $('#id_task_amount').prop('disabled',false).css("background-color","#FFFACD");
然而问题在于每个字段 id 也是动态生成的,看起来像 id_task_size_edit_1、id_task_size_edit_2 和 id_task_amount_1 等。
我认为我可以在 select 中使用通配符或像这样捕获所有以 id_task_size_edit 开头的事件
$(document).on('click',"'input[id^=id_task_size_edit]'",function(){
然而那是行不通的。我还尝试了 [id*=id_task_size_edit] 有和没有 "input" 语法和通配符的更多组合,但似乎没有任何效果。我要么遗漏了某些东西,要么无法将通配符传递给 select 或 jquerys .on 函数的字段。
如何使用动态生成的 ID 将事件绑定到动态生成的字段?
而不是 ID
,给他们一个通用的 class
,然后在您的 JQuery:
中使用它
$(document).on('click','.some_common_class_name',function(){
只需将 "'input[id^=id_task_size_edit]'"
替换为 '[id^="id_task_size_edit"]'
。下面的工作示例。
$(document).on('click', '[id^="id_task_size_edit"]', function() {
$(this).text("It is working!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="id_task_size_edit_1" type="button">Click Me</button>
我有一个动态生成的表单,它根据用户输入呈现字段。我无法将事件直接绑定到动态生成的字段,因为在首次呈现 DOM 时它们不存在。但是,我可以使用 jquery 的“.on”方法通过像 document.This 这样的父元素绑定事件,因为“.on”接受 selector 到 select子元素"
.on( events [, selector ] [, data ], handler )
在我的测试中,我可以传入静态 selector 并像这样成功绑定事件。
$(document).on('click','#id_task_size_edit',function(){
// $('#id_task_amount').prop('disabled',false).css("background-color","#FFFACD");
然而问题在于每个字段 id 也是动态生成的,看起来像 id_task_size_edit_1、id_task_size_edit_2 和 id_task_amount_1 等。
我认为我可以在 select 中使用通配符或像这样捕获所有以 id_task_size_edit 开头的事件
$(document).on('click',"'input[id^=id_task_size_edit]'",function(){
然而那是行不通的。我还尝试了 [id*=id_task_size_edit] 有和没有 "input" 语法和通配符的更多组合,但似乎没有任何效果。我要么遗漏了某些东西,要么无法将通配符传递给 select 或 jquerys .on 函数的字段。
如何使用动态生成的 ID 将事件绑定到动态生成的字段?
而不是 ID
,给他们一个通用的 class
,然后在您的 JQuery:
$(document).on('click','.some_common_class_name',function(){
只需将 "'input[id^=id_task_size_edit]'"
替换为 '[id^="id_task_size_edit"]'
。下面的工作示例。
$(document).on('click', '[id^="id_task_size_edit"]', function() {
$(this).text("It is working!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="id_task_size_edit_1" type="button">Click Me</button>