[英]onchange event not working in dropdown menu added from another php page using jquery
我想在下拉菜單中顯示數據庫中的所有表列表,並允許用戶選擇表名。 當用戶選擇表名時,我想顯示所有數據。 html文件是這樣的
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$.ajax({url:"home.php?id=1",
success:function(result){
$("#div1").html(result);
}});
$("#dropdown").change(function(){
alert("list item selected");
$.ajax({url:"home.php?id=2&tablename="+tableForm.tableLists.value,
success:function(result){
$("#div2").html(result);
}});
});
});
</script>
</head>
<body>
<button value="add" >
<form name="tableForm">
<div id="div1"></div>
</form>
</button>
<br><hr>
<div id="div2"></div>
</body>
此頁面運行正常並顯示屬於數據庫的所有表名稱列表。 但是當我從下拉列表中選擇一個值時,它甚至不會提醒“已選擇列表項”消息。 怎么做才能讓它工作?
這是下拉列表的圖像
看起來下拉框是動態加載到頁面中的,因此您必須使用.on()
將該函數綁定到動態添加的元素:
$(document).on('change', '#dropdown', function(){
console.log("list item selected");
// do whatever here
});
我認為下拉框是動態加載到頁面中的。 你可以這樣使用
$("#dropdown").on('change',function(){
alert("hoi");
$.ajax({url:"home.php?id=2&tablename="+tableForm.tableLists.value,
success:function(result){
$("#div2").html(result);
}});
});
由於您的代碼表明您正在動態填充下拉列表,並且在您的代碼中,您提供了一個不起作用的本地事件,如果我必須在這種情況下工作,還有其他幾個事件處理程序,如.on
.bind
.live
等我肯定更喜歡使用.on
或.live
所以你的代碼必須是這樣的:
$("#dropdown").live('change',function(){
alert("list item selected");
$.ajax({
url:"home.php?id=2&tablename="+tableForm.tableLists.value,
success:function(result){
$("#div2").html(result);
}
});
});
或這個:
$("#dropdown").on('change',function(){
alert("list item selected");
$.ajax({
url:"home.php?id=2&tablename="+tableForm.tableLists.value,
success:function(result){
$("#div2").html(result);
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.