美好的一天,我在我的ajax代码上遇到这个奇怪的问题请看看:
$(".productDropdown").bind("change", productDropdown);
function productDropdown(){
$.get('/api/productDropdown',
{ option: $(this).val() },
function(data) {
var parent = $(this).parents('tr');
var qty = $(parent).find('input.qty').val();
var price = $(parent).find('input.price').val();
var description = $(parent).find('textarea.description').val();
console.log(price+":"+qty+":"+description);
});
}
日志结果是:
undefined:undefined:undefined
但是当我在get函数之外声明变量时,我可以得到正确的值。但我仍然无法在文本框中分配它们。因为当我尝试推杆时:
description.val(data.description);
在变量下面我得到了这个错误:
Uncaught TypeError: Cannot call method 'val' of undefined
(这是一个外部的js文件)
(修订版)
继承我的HTML文件:
<table id="tblContacts" class="table-responsive table table-striped table-bordered tablesorter table-hover col-lg-12">
<thead>
<tr>
<th class="col-lg-3">Product Name</th>
<th class="col-lg-4">Description</th>
<th class="col-lg-1">Quantity</th>
<th class="col-lg-1">Price</th>
<th class="col-lg-3">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<script type="text/javascript">
var my_var = {"":"Please select","1":"Paracetamol","2":"Biogesic","3":"Bioflu","4":"Medicol"};
</script>
<select class="form-control productDropdown" placeholder="Company Name" id="productId" required="required" name="product[0][name]">
<option value="" selected="selected">Please select</option>
<option value="1">Paracetamol</option>
<option value="2">Biogesic</option>
<option value="3">Bioflu</option>
<option value="4">Medicol</option>
</select>
</td>
<td><textarea name='product[0][description]' class="form-control description" rows="1" required></textarea>
</td>
<td><input type='number' min="1" max="9999" name='product[0][quantity]' class="form-control qty" required value="52"></td>
<td><input type='number' min="0.5" max="9999" name='product[0][price]' class="form-control price" required/></td>
<td>
<a href="#" class="btnRemoveRow btn btn-danger">Remove</a>
</td>
</tr>
</tbody>
</table>
任何想法请...非常感谢您的帮助。非常感谢您的时间。
答案 0 :(得分:1)
$(this)
不是您所期望的。您需要在$.get
之前定义一个变量,并在成功函数中使用它:
$(".productDropdown").bind("change", productDropdown);
function productDropdown() {
var target = $(this);
$.get('/api/productDropdown', {
option: $(this).val()
}, function (data) {
var parent = target.parents('tr');
var qty = $(parent).find('input.qty').val();
var price = $(parent).find('input.price').val();
var description = $(parent).find('textarea.description').val();
console.log(price + ":" + qty + ":" + description);
});
}
答案 1 :(得分:1)
试试这个:
$(".productDropdown").bind("change", productDropdown);
function productDropdown(){
var $this = $(this);
$.get('/api/productDropdown',
{ option: $this.val() },
function(data) {
var parent = $this.parents('tr');
var qty = $(parent).find('input.qty').val();
var price = $(parent).find('input.price').val();
var description = $(parent).find('textarea.description').val();
console.log(price+":"+qty+":"+description);
});
}