我有一个显示产品的模态和一个用于选择项目数的计数器。有向上和向下按钮来增加或减少数量。这是模式:
<div id="productDetailModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="productDetailModal" aria-hidden="true">
<div id="productDetailDialog" class="modal-dialog">
<div class="modal-content">
<div id="counter" class="col-xs-6">
<label for="qty"><abbr title="Quantity">Qty</abbr></label>
<input id="qty" value="0" />
<button id="down" onclick="modify_qty(-1)">-1</button>
<button id="up" onclick="modify_qty(1)">+1</button>
</div>
这是脚本函数:
function modify_qty(val) {
var qty = document.getElementById('qty').value;
var new_qty = parseInt(qty, 10) + val;
if (new_qty < 0) {
new_qty = 0;
}
console.log("Inside script.js function. new_qty= " + new_qty);
document.getElementById('qty').value = new_qty;
return new_qty;
}
如果我使用#counter
div
并将其放在html页面的正文中,则计数器可以正常工作。它只在模态中,它不起作用。我在函数中输出到控制台,似乎函数没有在模态中调用。我做错了什么?
答案 0 :(得分:0)
你没有显示你如何/在哪里包含javascript,但是如果你确定它在范围内(检查你的控制台日志中的错误),它应该可以工作。
这是一个有效的例子: jsfiddle.net
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#productDetailModal">Open Modal</button>
<div id="productDetailModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="productDetailModal" aria-hidden="true">
<script>
function modify_qty(val) {
var qty = document.getElementById('qty').value;
var new_qty = parseInt(qty, 10) + val;
if (new_qty < 0) {
new_qty = 0;
}
console.log("Inside script.js function. new_qty= " + new_qty);
document.getElementById('qty').value = new_qty;
return new_qty;
}
</script>
<div id="productDetailDialog" class="modal-dialog">
<div class="modal-content">
<div id="counter" class="col-xs-6">
<label for="qty"><abbr title="Quantity">Qty</abbr></label>
<input id="qty" value="0" />
<button id="down" onclick="modify_qty(-1)">-1</button>
<button id="up" onclick="modify_qty(1)">+1</button>
</div>
</div>
</div>
</div>