jquery:使用"letters"作为id

tes*_*mus 2 jquery jquery-selectors

我正在构建菜单,显示一个字母列表,然后根据用户选择的内容加载正确的页面.我能够加载一个字母,但我怎么能使用"字母"作为id,所以我不需要为每个字母复制相同的jquery代码.

<div id="idshow"><a id="hidelinks" href="#">Hide</a> <br /><br /></div>

<div id="letter_a"><a id="success_a" href="#">A Show</a></div>
<div id="letter_b"><a id="success_b" href="#">B Show</a></div>
<div id="letter_c"><a id="success_c" href="#">C Show</a></div>

<div id="loadpage"></div>


<script>
$("#idshow").hide();

$("#success_a").click(function () {

        $("#idshow").show();
        $("#letter").hide();


        $("#loadpage").load("letter_a.html", function(response, status, xhr) {
                if (status == "error") {var msg = "Sorry but there was an error: ";$("#error").html(msg + xhr.status + " " + xhr.statusText);}});
        });

        $('#hidelinks').click(function() {
                $('#letter_content').slideUp();
                $("#idshow").hide();
                $("#letter").show();
});

</script>
Run Code Online (Sandbox Code Playgroud)

Den*_*ret 5

你可以用这个:

 $('[id^="success"]').click(function () {
     // the letter is the last character of the id
     var letter = this.id.slice(-1); 
     ...
     $("#loadpage").load("letter_"+letter+".html" ...
Run Code Online (Sandbox Code Playgroud)

  • +1优雅的解决方案,满足OP的精确要求. (2认同)
  • @Brian:这会直接为所有元素添加相同的事件处理程序.我没有反对意见,但在这种情况下,我的解决方案是最有效的. (2认同)