简体   繁体   中英

How to Append a Div in-between two Divs based on their ID's using Jquery?

If I have these objects:

<div id='1'></div>
<div id='2'></div>
<div id='3'></div>
<div id='4'></div>
<div id='5'></div>

I have a textbox:

<input type="text">

Where I type in the value: 3.5 to dynamically make (I have the code for this, the next part I need help with):

<div id='3.5'></div>

How can I attach it in this order below, without first checking to see the value of every div on the page?

<div id='1'></div>
<div id='2'></div>
<div id='3'></div>
<div id='3.5'></div>
<div id='4'></div>
<div id='5'></div>

Using:

$('#What Goes Here If I Dont know the elements on the page?').after('<div id='3.5'>Hey</div>');

Any help is appreciated,

Taylor

IDs in the DOM should not start with a number (they would not be valid).
They should start with a character A-Za-z and then they can have numbers, - and _ following.

but if you want to go your route try this:

var div = $("<div id='3.5'></div>");
div_id_after = Math.floor(parseFloat(div.get(0).id));

$('#'+div_id_after).after(div);

Here is a fiddle demo: http://jsfiddle.net/maniator/DPMV5/

这有什么问题?

  $('#3').after('<div id='3.5'>Hey</div>');

Firstly IDs aren't allowed to start with a number.

Ignoring that, if you are only allowing integers, it's easy, just take 1 from the value and insert it, then renumber the rest. Otherwise you'll have to walk the DOM to check the values of the others first.

that comparision to add is arithmetic, so unfortunelly you need to iterate over the divs you could do this. maybe you should do padding, like 3 = 300000, so 3.5 is 3500000, to do a best comparision.

Maybe something like that would work:

var text = yourTextBox.value;
if(var number = Number(text))
{
    $('#'+Math.floor(number)).after('<div id='+text+'>Hey</div>');
} 
else alert("wrong number");

But you should probably check first (with a regex) that the text within the textbox is a legitimate number…

updated. thanks Neal.

http://jsfiddle.net/FB8xG/3/

var newValue = 3.5;

var oldValue = Math.floor(newValue); //3

var oldValueID = ('#' + oldValue);
var newValueID = ('<div id="' + newValue + '">' + newValue + '</div>');

$(oldValueID).after(newValueID);

Live Demo

var input = "3.5";
var parent = Math.floor(input);
var dest = $('#div-'+parent);

dest.after(dest.clone().attr('id','div-'+input).text(input));

Note: This will only work once between integers. A more robust method DOES require looking at the IDs of all divs within the destination.

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