使用 .index 确定页面上的正确表

Determining the proper table on a page using .index

本文关键字:index 使用      更新时间:2023-09-26

我正在为客户开发一个简单的jQuery解决方案,它将信息从本页上的表格中传递:http://yft.ac/upcoming-workshops/,到本页上的"研讨会感兴趣"字段:http://yft.ac/contact-us/。我正在使用本地存储 API 执行此操作,但遇到了问题。

您会注意到,如果您单击"YFT招生见解"标题下的三个按钮中的任何一个,则所有信息都将转移到所需的输入中。但是,每当您单击"YFT密集应用研讨会"下方的按钮时,只会传递部分信息,而每当您单击"YFT领先优势"时,都不会传递任何信息。

这是我正在使用的代码:

即将举行的研讨会页面:

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); 
    }); 
});

以下示例显示单击的每个按钮的检索值:http://jsfiddle.net/jVJjZ/embedded/result/