我正在为一个客户开发一个简单的jQuery解决方案,该解决方案将从此页面上的表格中携带信息:http://yft.ac/upcoming-workshops/,到此页面上的“Workshop Interested”字段:http://yft.ac/contact-us/。我使用Local Storage API执行此操作但遇到了问题。
您会注意到,如果您点击“YFT Admissions Insights”标题下的三个按钮中的任何一个,则所有信息都会被转移到所需的输入。但是,每当您单击“YFT强化应用程序研讨会”下面的按钮时,只有某些信息被转移,并且每当您在“YFT Head Start”下单击时,所有信息都不是被遗弃。
以下是我正在使用的代码:
即将举办的研讨会页面:
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
类的多个实例而发生的(有三种)。
我很感激任何和所有帮助整理这个小问题,提前谢谢!
答案 0 :(得分:1)
你可以通过稍微不同地导航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);
});
});
以下示例显示了点击的每个按钮的检索值:http://jsfiddle.net/jVJjZ/embedded/result/