使用jQuery的HTML唯一id-解决此问题的更好方法



所以我使用这个漂亮的小部件来创建选项卡,但我的编辑器抱怨它无效,而且符合规范。正如你所看到的,我有两个名字相同的id。我的问题是,解决这个问题的正确方法是什么?

这是html

<ul id="tabs">
    <li><a href="javascript:void(0)" name="tab1">Stuff</a></li>
    {% if not is_passing %}
        <li><a href="javascript:void(0)" name="tab2">More Stuff</a></li>
    {% endif %}
</ul>
<div id="panes">
    <div id="tab1">Tab 1</div>
    <div id="tab2">Tab 2</div>
</div>
<script style="text/javascript">
    $(document).ready(function() {
        $("#panes").children("div").hide();         // Initially hide all content
        $("#tabs li:first").attr("id","current");   // Activate first tab
        $("#panes div:first").fadeIn();             // Show first tab content
        $('#tabs a').click(function(e) {
            e.preventDefault();
            if ($(this).closest("li").attr("id") == "current"){ //detection for current tab
                return false;
            }
            else{
                $("#panes").children("div").hide();     //Hide all content
                $("#tabs li").attr("id","");            //Reset id's
                $(this).parent().attr("id","current");  // Activate this
                $('#' + $(this).attr('name')).fadeIn(); // Show content for current tab
            }
            return false;
        });
    });
</script>

这里有两个问题:

  1. 在选项卡和选项卡内容上使用#current
  2. 选项卡名称属性和选项卡内容id相同

使用current的类而不是id

使用addClassremoveClasshasClass

当然,您必须将CSS从#current更改为.current

并使用rel而不是name。

<ul id="tabs">
    <li><a href="javascript:void(0)" rel="tab1">Stuff</a></li>
    {% if not is_passing %}
        <li><a href="javascript:void(0)" rel="tab2">More Stuff</a></li>
    {% endif %}
</ul>
<div id="panes">
    <div id="tab1">Tab 1</div>
    <div id="tab2">Tab 2</div>
</div>

<script style="text/javascript">
    $(document).ready(function() {
        $("#panes").children("div").hide();         // Initially hide all content
        $("#tabs li:first").addClass("current");   // Activate first tab
        $("#panes div:first").fadeIn();             // Show first tab content
        $('#tabs a').click(function(e) {
            e.preventDefault();
            if ($(this).closest("li").hasClass("current")){ //detection for current tab
                return false;
            }
            else{
                $("#panes").children("div").hide();     //Hide all content
                $("#tabs li").removeClass("current");            //Reset
                $(this).parent().addClass("current");  // Activate this
                $('#' + $(this).attr('rel')).fadeIn(); // Show content for current tab
            }
            return false;
        });
    });
</script>

相关内容

最新更新