简体   繁体   中英

Javascript inner.HTML not usable with a function - create moveable divs


I want to take a list of users from a database, show their name in a table and when you click on a name, a special div apeears with his details, you can move this div and even close it.

Here is a short scheme how the code is written:

function openDiv(id){
document.getElementById('divsHere').innerHTML +='< div id="moveable'+id+'"> content </div> '}

  <?php database connection... while{ 

...

 <tr onclick='openDiv( ". $row['id'] ." )'> $script += 'Drag.init(document.getElementById("moveable'+ $row['id'] +'"));' 

...

}?>

 <div id="divsHere"></div> 

echo $script;

I've used this awesome drag'n'drop library. http://www.dynamicdrive.com/dynamicindex11/domdrag/index.htm (note I have the same problems with jQuery)

It seems the drag'n'drop function doesn't work, when the div was addad by inner.HTML. However, I don't see any onther way around.

Thank you for any advice!

The problem is when you execute Drag.init the div you feed it is not yet created.

I sugest you generate the individual divs inside a php cycle, just like you do for the th tags, remove the setting of the innerHTML you have at the beginning of openDiv, and it'll work.

I have to say though, it seems like what you want is a modal dialog which you can find already made and easy to use elsewhere. For example: http://jqueryui.com/dialog/ It'll both be easier to work with and your likely to enjoy the final result more.

I hope this helps :)

Try adding the div using document.createElement :

var newDiv = document.createElement('div'), 
    textNode = document.createTextNode('content');
newDiv.id = "moveable" + id;
newDiv.appendChild(textNode);
document.getElementById('divsHere').appendChild(newDiv);

and to initialise the dragging simply do

Drag.init(newDiv);

provided that part of the code where you want to initialise the dragging has newDiv within its scope.

(Probably you want to create the div and initialise the possibility of dragging it in the same place. If I've understood your scheme right, then the problem is that it first tries to initialise dragging on non-existent divs, then only when the user clicks on a row, calling the function openDiv , are those divs created. If this is right then to fix it, you need to make sure the dragging is only initialised after the div has been created.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM