我不知道我怎么能找到上一个。使用jQuery编写“cmd and path”类。
这是我的HTML代码:
<tr>
<td>MySQL</td>
<td class="path">/etc/init.d/mysql</td>
<td class="cmd">status</td>
<td><i class="icon-remove"></i> <i class="icon-pencil"></i></td>
</tr>
我的jQuery代码看起来:
$('i.icon-pencil').click(function() {
var text = $(this).prev('.cmd').text();
alert(text);
});
答案 0 :(得分:2)
$('i.icon-pencil').click(function() {
var text = $(this).closest('td').prev('.cmd').text();
alert(text);
});
答案 1 :(得分:2)
$('i.icon-pencil').click(function() {
var tr = $(this).closest('tr'),
txtPath = tr.find('.path').text(),
txtCmd = tr.find('.cmd').text();
});
答案 2 :(得分:1)
您可以使用:
$('i.icon-pencil').click(function() {
var parent = $(this).parent(),
txtCmd = parent.prev('.cmd').text(),
txtPath = parent.prev('.path').text();
});
答案 3 :(得分:1)
您的代码中的问题是&#39; .cmd&#39;不适合你$(this)
它的上限为parent
。
$('i.icon-pencil').click(function() {
var text = $(this).parent().prev('.cmd').text();
alert(text);
});
答案 4 :(得分:0)
$('i.icon-pencil').click(function() {
var text = $(this).closest('tr').children('.cmd').text(); // .path can also be the selector.
alert(text);
});
另一种方法是使用.prevAll()
:
$('i.icon-pencil').click(function() {
var text = $(this).parent().prevAll('.cmd').text(); // .path can also be the selector.
alert(text);
});
答案 5 :(得分:0)
prev()无法正常工作,因为它不会遍历DOM树,您需要为此工作。你需要上升2级到tr,然后在子级中搜索“cmd”类的“td”标签。你的代码应该像这样工作......
$('i.icon-pencil').click(function() {
var text = $(this).parent().parent().children('.cmd').text();
alert(text);
});
希望有所帮助。