Javascript 使用.index确定页面上正确的表
我正在为客户机开发一个简单的jQuery解决方案,该解决方案将信息从本页的表转到本页的“Workshop Interest”字段。我使用本地存储API执行此操作,但遇到了一个问题 您会注意到,如果您单击“YFT招生洞察”标题下的三个按钮中的任何一个,则所有信息都将转入所需的输入。但是,每当您单击“YFT密集型应用程序研讨会”下方的按钮时,只有部分信息被传递,而每当您单击“YFT领先”下方的按钮时,没有任何信息被传递 以下是我正在使用的代码: 即将到来的研讨会页面:Javascript 使用.index确定页面上正确的表,javascript,jquery,html,forms,Javascript,Jquery,Html,Forms,我正在为客户机开发一个简单的jQuery解决方案,该解决方案将信息从本页的表转到本页的“Workshop Interest”字段。我使用本地存储API执行此操作,但遇到了一个问题 您会注意到,如果您单击“YFT招生洞察”标题下的三个按钮中的任何一个,则所有信息都将转入所需的输入。但是,每当您单击“YFT密集型应用程序研讨会”下方的按钮时,只有部分信息被传递,而每当您单击“YFT领先”下方的按钮时,没有任何信息被传递 以下是我正在使用的代码: 即将到来的研讨会页面: jQuery(function
jQuery(function ($) {
$('body').on('click', 'a.button', function () {
// Variables
var index = $(this).parents('table').index('table');
var buttonIndex = $("a.button").index(this);
buttonIndex+=1; //Add one to our index so we ignore the <tr> values in the <thead>
var cur_workshop_name = $(this).parents('.innercontent').find('h3').eq(index).text();
var cur_workshop_date = $(this).parents('.innercontent').find('tr:nth-of-type(' + buttonIndex + ') td:first-child').eq(index).text();
var cur_workshop_location = $(this).parents('.innercontent').find('tr:nth-of-type(' + buttonIndex + ') td:nth-of-type(3)').eq(index).text();
//Set Item in Local Storage
localStorage.setItem('workshop', cur_workshop_name + ' | ' + cur_workshop_location + ' | ' + cur_workshop_date);
});
});
jQuery(function ($) {
//Output value in respective field
$('#workshop').val( localStorage.getItem('workshop') );
});
我确实是用jQuery的中级技能拼凑起来的,但我认为问题的出现是因为页面上有多个表(有三个),或者是innercontent
类的多个实例(有三个)
我将感谢任何和所有的帮助来解决这个小问题,提前谢谢 通过稍微不同地导航DOM树,可以简化这一点
jQuery(function ($) {
$('body').on('click', 'a.button', function (event) {
var btn = $(this);
// get the closest table (unlike parents() this will go up the tree until it finds the first matched element and returns just that)
var table = btn.closest('table');
// get the closest row to the button (same as for the table)
var row = btn.closest('tr');
// the find the h3 by searching the previous siblings and stopping at the closest (using :first)
var cur_workshop_name = table.prevAll('h3:first').text();
// using the parent row search the child td elements for the required data
var cur_workshop_date = row.children('td:first-child').text();
var cur_workshop_location = row.children('td:nth-child(3)').text();
//Set Item in Local Storage
localStorage.setItem('workshop', cur_workshop_name + ' | ' + cur_workshop_location + ' | ' + cur_workshop_date);
});
});
下面是一个显示每个单击按钮的检索值的示例:考虑使用:n子(n)选择器挑出不同的表。非常感谢您的回答和详细的注释,以帮助我了解您所做的工作。这很好用。