这是我的表..我想清理jquery,以便我可以在表的html中的许多行上使用这个逻辑。
<table>
<tr>
<td class="check"><input class="select_service3 user_checkbox" type="checkbox"></td>
<td class="name">NAME</td>
<td class="duration">
<span class="duration3">30 min</span>
<a class="custom_duration_link3">Custom</a>
<span class="custom_duration_input3"><input class="custom" type="text"> min <button class="custom_duration_save3">Save</button></span>
</td>
<td class="price">$25 <a class="custom_price_link3">Custom</a></td>
</tr>
</table>
jquery的
$(".custom_duration_link3").hide();
$(".custom_price_link3").hide();
$(".custom_duration_input3").hide();
$(".select_service3").click(function(){
if ($(".select_service3").is(":checked"))
{
$(this).closest("tr").addClass("active");
$(".custom_duration_link3").show();
$(".custom_price_link3").show();
$('.custom_duration_link3').click(function(){
$('.custom_duration_link3').hide();
$('.duration3').hide();
$('.custom_duration_input3').show();
});
$('.custom_duration_save3').click(function(){
$('.custom_duration_input3').hide();
$('.duration3').show();
$('.duration3').addClass("notused");
});
}
else
{
$(this).closest("tr").removeClass("active");
$('.custom_duration_link3').hide();
$('.custom_duration_input3').hide();
$('.duration3').show();
$('.duration3').removeClass("notused");
$('.custom_price_link3').hide();
}
});
我该怎么做才能清理这段代码而不必“.duration1”,“。duartion2”等...
感谢您的帮助。
答案 0 :(得分:2)
基本上,使用函数中的this
对象来检索活动行。然后只引用该行范围内的类名。这是一个快速演示:
想法是使用这样的东西:
var current = $(this).closest("tr");
$(".custom_price_link",current).show();
答案 1 :(得分:1)
我知道你得到了答案但是如果你不想手动指定选择器并且将来它们的位置相同,那么你可以选择这个。
if ($(".select_service3").is(":checked"))
{
$(this).closest("tr").addClass("active");
$(this).parent()
.siblings('.duration').children(':not(:last)').show().end()
.children('a').click(function () {
$(this).parent()
.children().hide().end()
.children(':last').show()
.children('button').click(function () {
$(this).parent().hide().parent().children(':first').addClass('notused').show();
});
}).end()
.siblings(':last').children('a').show();
}
else
{
$(this).closest("tr").removeClass("active");
$(this).parent()
.siblings('.price').children('a').hide().end()
.siblings('.duration').children(':first').removeClass('notused').show().end()
.children(':not(;first)').hide();
}