2014-01-09 23 views
0

我有以下菜单系统。随着我向菜单添加更多步骤,我需要编写一个新功能。我如何编写一个函数来显示任何步骤的信息?我想提取每个id中的数字并将其传递给函数,但我不知道如何实现。任何帮助将是伟大的,谢谢!从功能中的ID访问号码

HTML:

<h3> 
    Step1 &nbsp;&nbsp;&nbsp; 
    <i id="step-info1">Info</i> 
</h3> 

<div id="step-info-cnt1" 
    style="margin-left: 13px; display: none; width: 420px;"> 
    <div> 
     <i id="step-info-close1">Close</i> 
    </div> 
    <div> 
     <ul> 
      <li>info item step 1A</li> 
      <li>info item step 1B</li> 
     </ul> 
    </div> 
</div> 

<h3> 
    Step2 &nbsp;&nbsp;&nbsp; 
    <i id="step-info2">Info</i> 
</h3> 

<div class="popup" id="step-info-cnt2" 
    style="margin-left: 13px; display: none; width: 420px;"> 
    <div> 
     <i id="step-info-close2">Close</i> 
    </div> 
    <div> 
     <ul> 
      <li>info item step 2A</li> 
      <li>info item step 2B</li> 
     </ul> 
    </div> 
</div> 

的Javascript:

$('#step-info1').click(function() { 
    $('#step-info-cnt1').show(); 
}); 
$('#step-info-close1').click(function() { 
    $('#step-info-cnt1').hide(); 
}); 

$('#step-info2').click(function() { 
    $('#step-info-cnt2').show(); 
}); 
$('#step-info-close2').click(function() { 
    $('#step-info-cnt2').hide(); 
}); 

JSFiddle

+0

正如Adeneo建议,你应该使用类 –

回答

3

this.id.slice(-1)获取事件处理程序

$('[id^="step-info"]').on('click', function() { 
    var numb = this.id.slice(-1); 
    $('#step-info-cnt' + numb).show(); 
}); 

$('[id^="step-info-close"]').on('click', function() { 
    var numb = this.id.slice(-1); 
    $('#step-info-cnt' + numb).hide(); 
}); 

和u内的数唱“属性开始”选择器,您可以选择多个元素。

使用类似乎更合适

$('.step-info').on('click', function() { 
    $(this).closest('h3').next('.popup').show(); 
}); 

$('.step-info-close').on('click', function() { 
    $(this).closest('.popup').hide(); 
}); 

FIDDLE

+0

犯规,这限制如果您使用基于0的索引,最多10个元素?如果你认为我的答案足以得到这个数字(使用正则表达式),你可以将它纳入你的答案,我会删除我的。 –

+1

@JosephMarikle - 你是对的,它确实只限制一个数字,所以只有0-9。至于正则表达式,我想我可能会做'/ \ d +/.exec(this.id)',但类似乎是要走的路。 – adeneo

1

我会使用一个正则表达式来提取它

this.id.match(/[0-9]+$/) 
1

你可以使用任何可用的jQuery的号码选择的。

例如,使用CSS类:

<div class="step-info" style="margin-left: 13px; display: none; width: 420px;"> 
    <div> 
     <i class="step-info-close">Close</i> 
    </div> 
    <div> 
     <ul> 
      <li>info item step 1A</li> 
      <li>info item step 1B</li> 
     </ul> 
    </div> 
</div> 
<!-- and so on --> 

你的JavaScript会再看看这样的:

$('.step-info').click(function() { 
    $(this).children('.step-info-close').show(); 
}); 
$('.step-info-close').click(function() { 
    $(this).parents('.step-info:first').hide(); 
}); 
0

没有必要继续计数。 您也可以使用类并定位您点击的元素。

尝试用类替代ID和使用下面的代码:

$('.step-info').click(function() { 
$(this).parent().next().toggle(); 
}); 
$('.step-info-close').click(function() { 
$(this).parent().parent().toggle(); 
//alert($(this).parent().attr("class")); 
}); 

看到以下小提琴

http://jsfiddle.net/SK8YN/3/