我在动态生成的表内的文本框中存储变量时遇到一些问题。
我的目标是,我想从动态生成的表内的文本框中获取值,然后将其存储到数据库中。
我的问题是,我可以使用
来输入文本框的值 $(this).closest('tr').find("input").each(function() {
var stock = $(this).val();
})
但是当我在函数外部调用它时,库存值不会存储在变量中。
这是检索数据的代码
$(document).on("click", ".tambahSparepart", function(event){
$(this).closest('tr').find("input").each(function() {
var stock = $(this).val();
})
alert('stock');
})
这是生成文本框的HTML代码
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Stock Code</th>
<th style="padding-right: 265px">Stock Description</th>
<th>UM</th>
<th>Stock Available</th>
<th>Need</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
foreach ($data->result() as $row) {;?>
<tr>
<td><?php echo $row->stock_code;?></td>
<td><?php echo $row->stock_description;?></td>
<td><?php echo $row->um;?></td>
<td><?php echo $row->stock;?></td>
<td>
<input type="text" name="stock" class="form-control" placeholder="Stock...">
</td>
<td>
<button class="tambahSparepart btn btn-block btn-default"
stock_code="<?php echo $row->stock_code;?>"
>
Tambah
</button>
</td>
</tr>
<?php }
;?>
</tbody>
<tfoot>
<tr>
<th>Stock Code</th>
<th>Stock Description</th>
<th>UM</th>
<th>Stock Available</th>
<th>Need</th>
<th>Actions</th>
</tr>
</tfoot>
</table>
谢谢
答案 0 :(得分:1)
变量在执行上下文中限定作用范围,因此,当您创建变量并为其分配值时,实际上(至少)具有两个上下文:
// Here is the global scope of execution, assuming all of this does not happen in another function:
var outerVar = 123;
$(this).closest('tr').find("input").each(
function() {
// Here you define another context of execution by declaring a function, that is a piece of code that is not executed right away, thus needs a different context.
// Here you are executing your function multiple times inside a loop, so there will be multiple assignment of some value to different variables all named 'stock'
var stock = $(this).val();
// Inside this function you will have access to the outer and inner context variables
console.log(outerVar, stock) // 123, 'some value'
}
)
// Outside the function you will not have access to the function's inner context variables
console.log(outerVar, stock) // 123, undefined
因此,如果希望两个上下文进行通信,则可以在外部作用域上创建一个变量,然后从内部作用域对其进行更新。这是您的情况的一个示例:
// Here we defined a global variable, and since we are going to have multiple values, we give it an empty array as value.
var stocks = [];
$(this).closest('tr').find("input").each(
function() {
var stock = $(this).val();
// At each iteration we push the current value of stock into the global array
stocks.push(stock);
}
)
console.log(stocks);
希望这会有所帮助!
答案 1 :(得分:0)
替换您的代码:
$(document).on("click", ".tambahSparepart", function(event){
$(this).closest('tr').find("input").each(function() {
var stock = $(this).val();
})
alert('stock');
})
对此:
$(document).on("click", ".tambahSparepart", function(event){
var stock = $(this).closest('tr').find("input").val();
alert(stock);
});