我正在创建一个依赖项下拉列表,
当我将Id从一个函数传递给另一个函数时,它不起作用,下面是一些代码示例
<?php
include("includes/db.php");
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div>
<select id="all_category">
<option>select a category</option>
</select>
</div>
<script type="text/javascript">
$(document).ready(function(){
category();
function category(){
$.ajax({
url : "action.php",
method : "POST",
data : {category:1},
success : function(data){
$("#all_category").html(data)
}
})
}
$("#all_category").change(function () {
var val = $(this).val();
var xyz = $("#all_category option:selected").val();
console.log("hello"+xyz)
})
})
</script>
</body>
</html>
这段代码是从API
中获取数据,
当我从第一个下拉列表中打印ID时,
它只是在console.log中我的Id变量之前打印消息
<?php
include "../db.php";
if (isset($_POST["category"])) {
$get_assign_course = "SELECT * FROM categories";
$run_p_cats = mysqli_query($con,$get_assign_course);
while ($rows=mysqli_fetch_array($run_p_cats)) {
$cat_id = $rows['cat_id '];
$cat_title = $rows['cat_title'];
echo "<option value='$cat_id '>$cat_title</option>
";}}
?>
这就是我的API
帮助?
发布于 2021-04-03 18:14:49
尝试将其更改为:$(“#all_category”).change(函数为:
$("#all_category").on('change',function
或者试试这个:
$(document).on('change','#all_category',function(){
如果这对你有效,请告诉我
发布于 2021-04-03 18:42:39
当您在jQuery中使用.html()
时,它将销毁事件上已经发生的任何绑定。这是因为html
删除了DOM树,并用数据重新初始化它。
<script type="text/javascript">
$(function() {
$.ajax({
url: "action.php",
method: "POST",
data: {category: 1},
success: function (data) {
$("#all_category").html(data);
$("#all_category").on('change', function (evt) {
console.log($(this).val())
})
}
});
});
</script>
要解决此问题,您需要在进行.html()
调用后重新绑定。
https://stackoverflow.com/questions/66934386
复制相似问题