为什么 val() 函数不适用于稍后呈现的 html?

问题描述

所以我有一个用 javascript 渲染的加减按钮,因为我需要来自数据库的数据,如果我不使用 javascript 渲染它,它会起作用,但它不起作用。

HTML:

<div id="cart">
  <div class="row">

  </div>  
</div>

JS(渲染):

var output = [];
var food_template = [];
//res is the data got from database
for(var f in res) {
  id = res[f]["id"];
  name = res[f]["name"];
  description = res[f]["description"];
  price = res[f]["price"];
  food_template = [
    '<div class="col-6">','    <div class="single_food_item media">','        <div class="media-body",style="margin-right:10px; margin-top: 20px; height: 200px">',`            <h3>${name}</h3>`,`            <p>${description}</p>`,`            <h5>$${price}</h5>`,//add minus button starts
    '            <div class="input-group" style="width:50%">','                <span class="input-group-btn">','                    <button class="btn btn-danger btn-minus" type="button">-</button>','                </span>','                <input type="text" class="form-control no-padding add-color text-center height-25" maxlength="3" value="0">','                    <button class="btn btn-success btn-plus" type="button">+</button>','            </div>',//add minus button ends
    '        </div>','    </div>','</div>'
  ];
  output.push(food_template.join("\n"));
}
("#cart .row").html(output.join("\n"));

JS(添加减号按钮):

$('#cart .row').delegate('.btn-minus','click',function(){
  $(this).parent().siblings('input').val(parseInt($(this).parent().siblings('input').val()) - 1);
});

$('#cart .row').delegate('.btn-minus',function(){
  $(this).parent().siblings('input').val(parseInt($(this).parent().siblings('input').val()) + 1)
});

调用所有函数

我的测试让我认为问题可能是 val() 函数没有改变输入 HTML 的值,因为如果我使用 console.log 来显示它可以工作但它不会在网络上更新

解决方法

我认为减号按钮上有加号和减号事件处理程序,所以当你点击它时,加号处理程序增加值,减号处理程序减少它,因此你看不到有关值的变化输入