Jquery,$(this).next问题

时间:2010-03-03 14:19:53

标签: jquery

尝试在此处截断某些代码并遇到问题:

<script type="text/javascript">
  $(function() {
  $('#a1').click(function() {
    $(this).next('#desCopy').appendTo('#description');
    $(this).next('#imgPlace').appendTo('#IMGbox');
    return false;
  });
});
</script>

    <!--Content-->


    <div id="content" style="background:#000; width:989px;">

        <div style="float:left; left:18px; margin:0; width:337px; position:relative; padding:15px 0 0 0; color:#FFF;">


            <div id="description">

            </div>

        </div>

        <div id="IMGbox" style="float:left; position:relative; display:block; background:#F00; width:652px; height:258px; background:#0FF; overflow:hidden;">



        </div>

        <div style="float:right; background:#CCC; height:25px; width:652px;">

            <ul>

                <li><a id="a1" href="#">Slide 1</a>
                    <ul style="display:none;">
                        <li><span id="desCopy">Test description, Test description</span></li>
                        <li><img src="images/test.jpg" id="imgPlace"></li>
                    </ul>
                </li>

                <li><a id="a1" href="#">Slide 2</a>
                    <ul style="display:none;">
                        <li><span id="desCopy">2222, 22222</span></li>
                        <li><img src="images/test2.jpg" id="imgPlace"></li>
                    </ul>
                </li>

            </ul>

        </div>


    </div>

2 个答案:

答案 0 :(得分:5)

您不能多次使用相同的ID,它是无效的HTML,并且各种事情都不会正常运行,包括jQuery ID选择器。您可能希望使用类,如下所示:

<span class="desCopy">
<img class="imgPlace">

然后你可以这样做:

$(function() {
  $('#a1').click(function() {
    $(this).parent().find('.desCopy').appendTo('#description');
    $(this).parent().find('.imgPlace').appendTo('#IMGbox');
    return false;
  });
});

答案 1 :(得分:0)

所以我想要的结果是简单地在我的ul和我定义的ID div之间来回切换内容。

尼克提出的一个好处是,我使用相同的ID,这是主要原因。 所以我用以下代码将我的锚ID转换为类,并得到了我需要的最终结果。

$(function() {
  $('.a1').click(function() {
    $('#description').find('.desCopy').hide();
    $('#IMGbox').find('.imgPlace').hide();
    $(this).parent().find('.desCopy').clone().appendTo('#description');
    $(this).parent().find('.imgPlace').clone().appendTo('#IMGbox');
    return false;
  });
});