【问题标题】:Why val() function doesn't work with later rendered html?为什么 val() 函数不适用于后来渲染的 html?
【发布时间】:2021-03-20 12:21:59
【问题描述】:

所以我有一个用 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">',
    '                <span class="input-group-btn">',
    '                    <button class="btn btn-success btn-plus" type="button">+</button>',
    '                </span>',
    '            </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', 'click', function(){
  $(this).parent().siblings('input').val(parseInt($(this).parent().siblings('input').val()) + 1)
});

(调用所有函数)

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

【问题讨论】:

  • 你好,两个事件处理程序都是为btn-minus ?

标签: javascript html jquery delegates


【解决方案1】:

我认为您将加号和减号事件处理程序都附加到减号按钮,因此当您单击它时,加号处理程序会增加值而减号处理程序会减少它,因此您看不到关于输入

【讨论】:

    猜你喜欢
    • 2020-07-11
    • 2012-12-06
    • 2019-01-25
    • 1970-01-01
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    相关资源
    最近更新 更多