javascript - id为动态时如何调用ajax
问题描述
我有两个带有添加更多按钮的输入字段。如果用户单击“添加”按钮,将显示另外两个具有不同 ID 名称的输入类型文本。
我在第二个输入字段上使用 keyup 功能。如果用户输入任何值,那么它将调用我的 ajax 函数。
现在我的问题是,动态时如何调用 ajax?我的意思是如何将 x 值发送到 ajax?我只是想知道
$("#total_p_price").keyup(function (){));
如何从动态调用?
检查当我第一次输入 number=2 和 total_p_price=10 并计算它并显示 single_price=5。
哪个是对的。现在我点击添加按钮。这次 number=4 和 total_p_price=100 计算它并显示 single_price=50。这也是正确的,但它也更新了第一个 single_price 字段。
HTML
<div class="add_row">
<input type="text" name="" id="number">
<input type="text" name="" id="total_p_price">
<input type="text" name="" id="single_price">
<div class="btn_row add_row_click"> <span> + </span> Add </div>
</div>
<script>
$(document).ready(function() {
var max_fields = 20; //maximum input boxes allowed
var wrapper = $(".add_row"); //Fields wrapper
var add_button = $(".add_row_click"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div class="custom_fields"><input type="text" name="" id="number' + x '"><input type="text" name="" id="total_p_price' + x '"><input type="text" name="" id="single_price' + x '"> <div class="btn_row remove_field"> <span> - </span> Remove </div></div>');
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
//$(this).parent('custom_fields').remove();
$(this).closest('.custom_fields').remove();
x--;
})
$("body").on('keyup', 'input[id^=total_p_price]', function() {
//$('input[id^=single_price]').prop('disabled', true);
var total_p_price = $(this).val();
var qty_number = $('input[id^=number]').val();
$.ajax({
type: "POST",
url: baseUrl + "/Customer_control/calculate_total_p_price",
data: {
total_p_price: total_p_price,
qty_number: qty_number
},
cache: false,
success: function(html) {
//alert(html);
$('input[id^=single_price]').val(html);
}
});
});
});
</script>
解决方案
根据我对您的问题的了解,您需要使用事件委托。就像是
$(".add_row").on("keyup","#total_p_price", function (){
var total_p_price= $(this).val();
$.ajax({
type : "POST",
url: baseUrl + "/Customer_control/calculate_total_p_price",
data: {total_p_price: total_p_price},
cache : false,
success: function(html) {
console.log(html);
}
});
});
您需要确保 add_row 元素是 HTML 中的静态元素。
推荐阅读
- mpi - mpiicpc 没有找到命令
- mongodb - Group by 两个单独的字段,两个单独的计数
- c - MPI_Gather C 中的结构数组
- javascript - 为什么实际网站会在重定向到另一个网站之前显示?
- c# - 如何在 ubuntu 18.04.2 上访问 nuget 包管理器控制台
- c# - DGV 数据绑定以及来自“嵌套”二级属性类的集合?
- python - 矢量化 numpys 卷
- java - 为什么我不能在 toString 方法中返回有价值的字符串类型?
- html - 作品集页面用户故事 7. 导航栏应包含至少一个链接,我可以单击该链接导航到页面的不同部分
- azure-service-fabric - 有人见过 Service Fabric 无状态服务实例在没有异常的情况下终止吗?