我还在学习jQuery,我遇到了一个问题。我有一个包含50+行的表。每个标签都标有一个id。
<tr id="51">这个id就是数据库id,我需要将它传递给jQuery并与AJAX请求一起提交。
$($location).click(function () {
var $currentSelection = $(this);
// if there is already an input-field in this TD, return...
if($currentSelection.find('select').length > 0)
return;
$currentSelection.html('');
$('<select id="selectLocation" onChange="locationSubmit()"/>')
.attr('name', 'location')
.append('<option>Location 1</option>', '<option>Location 2</option>', '<option>Location 3</option>')
.appendTo(this);
});locationSubmit()
function locationSubmit(){
var $selectLocation = $('#selectLocation').val();
var $selectId = $(this).val('tr#id'); //stuck here
alert($selectId);
$.ajax({
url: '/ajax/training-update.php',
data: {
action: $selectLocation,
courseid: $selectId
},
type: 'POST',
success: function(output) {
alert(output);
}
});
}locationSubmit()中的警报正在返回对象对象。如何将tr#id的值传递给locationSubmit()并通过AJAX发送?
编辑- HTML
<tr id="51">
<td><a href="/link/goes/here.php?course_id=5&id=51">course name</a></td>
<td>
<span class="rowStartDate" id="rowStartDate151">09/10/12</span> -
<span class="rowEndDate" id="rowEndDate151">09/14/12</span>
</td>
<td class="location">Location 2</td>
<td class="status">open</td>
</tr>发布于 2012-09-11 06:53:45
那么,有什么好的答案吗?
测试一下:
$($location).click(function () {
var $currentSelection = $(this);
// if there is already an input-field in this TD, return...
if($currentSelection.find('select').length > 0)
return;
$currentSelection.html('');
$('<select id="selectLocation"/>')
.attr('name', 'location')
.append('<option>Location 1</option>', '<option>Location 2</option>', '<option>Location 3</option>')
.appendTo(this);
});并将您的函数替换为:
$('body').delegate('#selectLocation', 'change', function(){
var $selectLocation = $(this).val(); //Edited here also
var $selectId = $(this).closest('tr').attr('id'); //edited here
alert($selectId);
//The AJAX here
});正如你所看到的,你的函数已经不存在了,取而代之的是委托,这看起来很不错!.delegate()是一个一直在工作的非常好的函数,即使元素是在DOM准备好之后创建的。它一直在监听
编辑的检查第二个代码部分。
发布于 2012-09-11 06:55:12
var $selectId = $('#selectLocation').parent("tr").attr("id")但是只有数字的in不是好的做法。
和!!
您正在创建多个ids。每个文档只能定义一个。
使用:
$($location).on("click" ...使用动态对象的步骤
更改:
$('<select class="selectLocation"然后
$(".selectLocation").change(function()
{
var $selectLocation = $(this).val();
var $selectId = $(this).parent("tr").attr('id');
alert($selectId);
$.ajax({
url: '/ajax/training-update.php',
data: {
action: $selectLocation,
courseid: $selectId
},
type: 'POST',
success: function(output) {
alert(output);
}
});
}https://stackoverflow.com/questions/12360528
复制相似问题