尝试使用 JQuery insertBefore() 方法添加 HTML 代码,但运行后 HTML 字符串变得混乱
在此循环中,我尝试向每个“计数”添加一个事件处理程序。事件处理程序调用函数“hideAll()”,其输入值为“count”。
我通过使用 JQuery 的 insertBefore() 方法在 ID“next”下添加 HTML 代码来实现此目的。
for (count=1; count<=3; count++)
{
$('<a href="#" onclick="hideAll(' + count + ');return false;">' + count + '</a>').insertBefore("#next");
}
因此,当我运行它时,它会被添加,但由于某些奇怪的原因,它会像这样添加:
<a onclick="hideAll(1);return false;" href="#">1</a>
字符串 href="#" 被移动到末尾。我不明白为什么。
我尝试检查引号和所有内容。一切看起来都很完美,不知道为什么要这样做。
In this loop, I'm trying to add an event handler to each "count". The event handler calls a function "hideAll()", whose input value is "count".
I am doing so by adding HTML code under the ID "next", using JQuery's insertBefore() method.
for (count=1; count<=3; count++)
{
$('<a href="#" onclick="hideAll(' + count + ');return false;">' + count + '</a>').insertBefore("#next");
}
So when I run it, it gets added, but for some weird reason, it get's added like this:
<a onclick="hideAll(1);return false;" href="#">1</a>
The string href="#" is getting moved over to the end. I can't figure out why.
I tried checking the quotation marks and everything. Everything seems perfect, no idea why it's doing that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您在什么浏览器中查看它?
有些浏览器在查看 dom 时,会在解释标记后向您显示其“最终”源。
确保您“查看页面源代码”,而不是“检查元素”以获得纯粹的预解释标记。
但最终,属性的顺序是无关紧要的,所以它应该适合您的目的?
What browser are you viewing it in?
Some browsers, when viewing the dom, shows you its "final" source after it has interpreted the markup.
Make sure you "View Page Source", and not "Inspect Elements" to get the pure pre-interpreted markup.
Ultimately, though, the order of attributes are irrelevant, so it should be fine for your purposes?
如果您查看 jQuery 源代码,就会发现这就是您传入字符串时所调用的内容,
因此浏览器从
document.createElement()
中吐出的内容就是 jQuery 放在 DOM 上的内容。If you look at the jQuery source, this is what gets called when you pass in your string,
So whatever the broswer spits out of
document.createElement()
is what jQuery is putting on the DOM.这对你来说真的很重要吗?
问题是代码
不会在 #next 标记之前插入原始 HTML。
该命令
在内存中创建 DOM 元素并将其包装到 jQuery 选择器中。然后将其插入到页面的 DOM 树中。如何将其显示为字符串取决于浏览器。
Does it really matter for you?
The thing is that code
does not insert raw HTML before #next tag.
The command
creates DOM element in the memory and wraps it into jQuery selector. Then it being inserted into DOM tree of page. And how it is showed to you as string is up to browser.