获取上一个元素 jQuery 的内容
get the content of the prev element jquery
我在我的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/
希望这对:)有所帮助
相关文章:
- 简单的垂直上一个和下一个按钮代码点击上下移动jQuery
- 当两个单独的单词被放在目标上时,使用Jquery获取一个值
- 用键盘分页jQuery下一个和上一个控件.触发器('点击')不'不起作用
- JQuery关注上一个点击的输入错误
- JQuery.删除DOM树中的上一个同级
- 上一个函数完成后,javascript/jQuery调用execute函数
- jQuery UI 选项卡取消选择事件或在选择时保存上一个选项卡
- jQuery UI 选项卡 - 将参数设置为下一个/上一个按钮单击
- 获取上一个元素 jQuery 的内容
- 获取下一个或上一个隐藏元素的高度,以设置父元素的高度.jquery.
- 遍历下一个和上一个 jQuery 选项卡
- JQuery,引导导航 - 如何添加上一个/下一个按钮
- jQuery网站的键盘快捷键,焦点使用左键和右键转到上一个或下一个元素
- 如何使用 jQuery 选择上一个 LI
- Jquery上一个对象选择器
- Jquery下一个和上一个按钮循环函数
- jquery scrolltop()返回上一个滚动位置的值
- 使jQuery图像滑块停止在最后一个图像,并添加下一个和上一个按钮
- Jquery UI选项卡&选择方框-下一个/上一个按钮
- Fullcalendar jQuery上一个和下一个按钮