如何使用 Jquery 根据 ID 在两个 Div 之间追加一个 Div?
如果我有这些对象:
<div id='1'></div>
<div id='2'></div>
<div id='3'></div>
<div id='4'></div>
<div id='5'></div>
我有一个文本框:
<input type="text">
在其中输入值: 3.5 来动态生成(我有这方面的代码,下一部分需要帮助):
<div id='3.5'></div>
如何按此顺序附加它下面,没有首先检查页面上每个 div 的值?
<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>
使用:
$('#What Goes Here If I Dont know the elements on the page?').after('<div id='3.5'>Hey</div>');
感谢任何帮助,
泰勒
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
DOM 中的 ID 不应以数字开头(它们无效)。
它们应该以字符
A-Za-z
开头,然后可以有数字、-
和_
。但如果你想走你的路线试试这个:
这是一个小提琴演示: http://jsfiddle.net/maniator /DPMV5/
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:
Here is a fiddle demo: http://jsfiddle.net/maniator/DPMV5/
这有什么问题吗?
What is wrong with this ?
首先,ID 不允许以数字开头。
忽略这一点,如果只允许整数,很简单,只需从值中取出 1 并插入它,然后对其余部分重新编号。否则,您必须先遍历 DOM 来检查其他值。
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.
添加的比较是算术运算,因此不幸的是,您需要迭代可以执行此操作的 div。也许你应该做填充,比如 3 = 300000,所以 3.5 是 3500000,以进行最佳比较。
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:
But you should probably check first (with a regex) that the text within the textbox is a legitimate number…
现场演示
注意:这只能工作一次在整数之间。更可靠的方法确实需要查看目标中所有 div 的 ID。
Live Demo
Note: This will only work once between integers. A more robust method DOES require looking at the IDs of all divs within the destination.
已更新。谢谢尼尔。
http://jsfiddle.net/FB8xG/3/
updated. thanks Neal.
http://jsfiddle.net/FB8xG/3/