2013-05-13 26 views
2

我不知道如何找到prev。类“cmd和路径”与jQuery。如何找到prev。与jQuery类

这里是我的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); 
}); 

回答

2
$('i.icon-pencil').click(function() { 
    var text = $(this).closest('td').prev('.cmd').text(); 
    alert(text); 
}); 

Fiddle

+0

谢谢,效果很好。 – Evolutio 2013-05-13 13:00:27

+0

这不会给出'.path'的机会。 – andlrc 2013-05-13 13:01:23

+1

http://jsfiddle.net/Ep9F9/3/ – 2013-05-13 13:08:15

1

你可以使用:

$('i.icon-pencil').click(function() { 
    var parent = $(this).parent(), 
     txtCmd = parent.prev('.cmd').text(), 
     txtPath = parent.prev('.path').text(); 
}); 
+0

这没有给出'.path'的机会。 – andlrc 2013-05-13 13:01:52

+0

@NULL谢谢,修正。 – Eli 2013-05-13 13:04:46

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); 
}); 
2
$('i.icon-pencil').click(function() { 
    var tr = $(this).closest('tr'), 
     txtPath = tr.find('.path').text(), 
     txtCmd = tr.find('.cmd').text(); 

}); 
+0

这是一个很好的答案。你可以考虑使用'.children'而不是'.find' – andlrc 2013-05-13 13:02:37

1

的问题,在你的代码是 '.CMD' 不上一个以你的$(this) 其分组到parent

$('i.icon-pencil').click(function() { 
    var text = $(this).parent().prev('.cmd').text(); 
    alert(text); 
}); 
0

prev()不工作,因为它没有遍历DOM树,您需要为此工作。你需要上升两级,到tr,然后搜索孩子的“td”标签与类“cmd”。你的代码应该像这样工作...

$('i.icon-pencil').click(function() { 
var text = $(this).parent().parent().children('.cmd').text(); 
alert(text); 
}); 

希望有所帮助。