开发者

jQuery appendTo (switching back and forth)

So what I'm trying to accomplish is a simple appendTo a certain element. The issue I'm having is after execute is run, it appends to the location but then proceed to go back to the ul it resides in.

<script type="text/javascript">
    function execute() {
      $('#desCopy').appendTo('#description')
      $('#imgPlace').appendTo('#IMGbox')
    }
</script>

<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 href="" onclick="execute()">Slide 1</a>
                <ul style="">
                    <li><span id="desCopy">Test description, Test description</span></li>
                    <li><img src="images/test.jpg" id="imgPlace"></li>
                </ul>
            </li>
        </ul>
    </div>
</div>


Change the event handler setup like this:

<a href="" onclick="execute(); return false">

Better yet, set it up with jQuery and have the handler return false:

// somewhere in your initialization code:
$(function() {
  $('#theAnchorTag').click(function() {
    $('#desCopy').appendTo('#description');
    $('#imgPlace').appendTo('#IMGbox');
    return false;
  });
});

You'd have to give your <a> an "id" value ("theAnchorTag" in my example), or you could identify it some other way in the selector where the "click" handler is set up. You're really better off using jQuery to bind event handlers; those "onfoo" attributes are pretty icky.


The problem is that an empty href (as is the case with your link) will reload the page when clicked..

So you rearrange your li elements and then the page gets reloaded reverting everything back to how they originally were..

As mentioned in the other answers you need to cancel the default click action by returning false from your handler..

You should also look to assigning the handler with jquery instead of inline attributes..


You have to return false from execute to prevent event bubbling.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜