获取上一个元素 jQuery 的内容

get the content of the prev element jquery

本文关键字:jQuery 上一个 元素 获取      更新时间:2023-09-26

我在我的html中有这个结构。

<table border="1" cellpadding="1" cellspacing="2">
<thead>
    <tr>
        <th>Name</th><th>Age</th><th>Address</th><th>Option</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>here is the name</td>
        <td>here is the age</td>
        <td>here is the address</td>
        <td><button class="update">update</button></td>
    </tr>
    <tr>
        <td>here is the name2</td>
        <td>here is the age2</td>
        <td>here is the address2</td>
        <td><button class="update">update2</button></td>
    </tr>
</tbody>
</table>

从上面的结构中可以看出,显示将是这样的。

table header = Name, Age, Address, Option.
table body = here is the name, here is the age, here is the address, button update
table body = here is the name2, here is the age2, here is the address2, button update2

现在我试图做的是当我单击更新按钮时,我必须能够获取地址 td 的内容以在同一行命名 td,并且每个都必须存储在指定的变量中,例如 ($name、$age、$address)。 假设我有多个行,我必须只能检索地址 td 的内容以命名同一行的 td。更准确地说,作为上面的结构,当我单击 u"update" 按钮而不是"update2"按钮时,我必须能够获取"这里是名称"、"这里是年龄"、"这里是地址"并将每个变量放在指定的变量中,例如 ($name、$age、$address)。

到目前为止,我尝试的是。

$('.update').click(function(){
   $address = $(this).prev('td').content();
   alert ($dateposted);
});

但似乎没有返回任何东西。任何帮助将不胜感激。谢谢!

这里this是按钮,它没有以前的兄弟姐妹,您要查找的td是单击按钮的td父级的前兄弟姐妹,您还必须使用.text()/.html()来获取内容

$address = $(this).parent().prev('td').text();//$(this).closest('td')

这是另一种方法。获取所有以前的div 后,循环它们以将值设置为正确的变量。

$('.update').click(function () {
    var contents = $(this).parent().prevAll('td');
    var name;
    var age;
    var address;
    for(i = 0; i<contents.length; i++){
        var currentContent = $(contents[i]);
        switch(i){
            case 0:
                name = currentContent.text();
                break;
            case 1:
                age = currentContent.text();
                break;
            case 2:
                address = currentContent.text();
                break;
        }
    }
    console.log(address, age, name);
});

有关工作示例,请参阅 http://jsfiddle.net/zeskysee/72j1oaqb/4/

希望这对:)有所帮助