开发者

use Jquery to insert div on my page to another part of my page

I am going to give a simple examp开发者_运维百科le of what I want to do.

I have this table. Static. I have five button and five corrisponding divs. When I click the button I want the table to be placed in the corrisponding div.

something like.

$("#button1").button().click($("#div1").append($("#mytable"));

and so on. Can this be done? How?

Also, Please tell me if there is a better way to do this, if I trying to re-invent the wheel or something like that...

WORKING:

The code I ended up using, based off of solutions:

$("#test").button().click(function() { $("#test2").append($("#table_EditInformation")); });

test is a button test2 is a div table_EditInforation is obviously a table


for a working example copy the html/js below into a "index.html" or any .html file and try it out.

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" ></script>
<script>
$(document).ready(function(){
 $("#button1").click(function () {
         $("#div1").empty().append($("#mytable"));
});
});
</script>
</head>
<body>
<a href="#" id="button1">the link or button to be pressed</a>
<div id="div1">
   <p>stuff should be put here</p>
</div>
<table id="mytable">
   <tr>
      <td>put my table in the div please! </td>
   </tr>
</table>
</body>
</html>

the plain javascript code is following:

    $("#button1").click(function () {
     $("#div1").append($("#mytable"));
   });

remember, the element with the id $("#mytable") must be in the same dom tree.

also you can use .empty() before .append() to empty out the content of #div

like this:

  $("#button1").click(function () {
     $("#div1").empty().append($("#mytable"));
   });

Check the documentation here jquery.html()


  $("#button1").click(function(){
    $("#div1").append($("#mytable"));
  });

Should do it for you


function appendTableTo(divId) {
  $('#mytable')
    .remove()             // take the table out of whatever div it's in
    .appendTo(divId);     // and place it into the right div
}

function addHandler(buttonId, divId) {
  $(buttonId).button().click(
    function(divId){
      return function(){
        appendTableTo($(divId));
      };
    }(divId)
  );
}

addHandler('#button1', '#div1');
addHandler('#button2', '#div2');
addHandler('#button3', '#div3');
addHandler('#button4', '#div4');
addHandler('#button5', '#div5');

This should do it. We have only one append function that places the table into the right div. Furthermore, we have a function that attaches this click handler to a button. And we call that five times.

The addHandler function uses a closure. That is necessary because we need to pass an argument to the appendTableTo function, and that is not possible otherwise.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜