我有一个简单的表单,其中有一个列表(从数据库生成的下拉列表),当用户进行选择时,该选择会打印在屏幕上。我遇到的问题是,如果我使用 jquery 调用在页面加载时生成列表的 php 函数,则该列表将不起作用,但如果我直接在 html 中添加代码,它将起作用
当页面加载时,下拉列表的调用如下:
$('#createDropDown').ready(function(){ id = $('#createDropDown').val(); // this calls a php function that creates a dropdown list from the DB // the dropdown's id = 'categoryList' xajax_addDropdownMenu(id);<p></p>
});
the list is generated with the id = 'categoryList', and it is appended correctly to the createDropDown DIV called "createDropDown". Up until now everything looks good! The problem comes when a selection is made on the newly created list (categoryList) another Jquery is called
when a selection is made the following code should be called:
$('#categoryList').change(function() {
bucket_id = $('#categoryList').val();
var selected = "";
// get selected value from the dropdown menu
$("#categoryList option:selected").each(function () {
selected += $(this).text() + " ===>";
});
// if we have a valid ID print it in the screen.
if(bucket_id!= 0)
{
xajax_addCategory(selected);
}
});
xajax_addCategory(selected); 在屏幕上打印所选项目。但不起作用。
注意:如果我调用 php 函数直接在 main.html 文件中生成下拉列表,那么我知道列表是使用正确的 ID 生成的并且它可以工作,但是当我使用 Jquery 调用时,这可以正常工作加载时的 php 方法不起作用...我不明白为什么。
PS 我是 Jquery 的菜鸟,所以非常欢迎一些见解!
<小时/>更新:
我尝试在生成列表后创建绑定(bind),如下所示:
$('#createDropDown').ready(function()
{
id = $('#createDropDown').val();
xajax_addDropdownMenu(id);
$("#categoryList0").bind('change',function()
{
console.log('The code goes here!!');
});
});
其中categoryList0 是新列表的ID。列表的类是categoryList
但我仍然陷入困境,因为当发生变化时它仍然没有进入函数......
最佳答案
您的第二个代码片段查找与 #categoryList 匹配的所有元素,并将函数绑定(bind)到更改事件。问题是当时没有 #categoryList 元素,因为您稍后创建了它。因此,您需要在创建列表后进行绑定(bind)。
关于javascript - 使用 jquery 创建时数据库生成的列表不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1267764/