简体   繁体   English

使用jQuery获取和设置内容的位置

[英]Getting and Setting position of Content with Jquery

I have a table with two rows, the first being the thead the second being the tbody (yes I know I have not included these tags, no need to correct). 我有一张两行的table ,第一行是thead ,第二行是tbody (是的,我知道我没有包含这些标签,不需要更正)。 My goal here is to get the position of each th . 我的目标是让每个位置th My overall all goal is to clone the content of each th and prepend it to each corresponding td , so I have a very mobile friendly table, except I do not know how to achieve this dynamically. 我的总体目标是克隆每个th的内容并将其添加到每个对应的td ,因此我有一个非常便于移动的表,除了我不知道如何动态实现。

<tr>
    <th>1</th>
    <th>2</th>
    <th>3</th>
    <th>4</th>
</tr>
<tr>
    <td>one</td>
    <td>two</td>
    <td>three</td>
    <td>four</td>
</tr>

I'm just confused on how I could get the position of each th , I think once I have that, I can solve the rest of this problem. 我对我怎么能拿每个位置只是困惑th ,我认为一旦我有,我可以解决这个问题的其余部分。 Can anyone give me a hint of where I should be going with this? 谁能给我提示我应该怎么做?

Assuming I've understood your question correctly, you want this output: 假设我正确理解了您的问题,则需要以下输出:

<tr>
    <th>1</th>
    <th>2</th>
    <th>3</th>
    <th>4</th>
</tr>
<tr>
    <td>1 - one</td>
    <td>2 - two</td>
    <td>3 - three</td>
    <td>4 - four</td>
</tr>

If so you need to use index() to get the column of the th and append as required. 如果是这样,则需要使用index()来获取th的列并根据需要追加。 Try this: 尝试这个:

$('tr td').each(function() {
    var idx = $(this).index();
    $(this).prepend($('th').eq(idx).text() + ' - ');
});

Example fiddle 小提琴的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM