gpt4 book ai didi

jquery - 将 id 传递给 jQuery

转载 作者:行者123 更新时间:2023-12-01 08:12:56 25 4
gpt4 key购买 nike

我仍在学习 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() 中的警报正在返回 [object Object]。如何将 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>

最佳答案

那么,有什么好的答案吗?

测试一下:

$($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)所取代,这似乎工作得很好! .delegate()这是一个非常好的功能,即使元素是在 DOM 准备好之后创建的,它也始终有效。它一直在听

已编辑检查第二个代码部分。

关于jquery - 将 <tr> id 传递给 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12360528/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com