使用 jquery 将表单插入页面?
我正在使用 jquery 将隐藏表单插入到页面中(一旦页面已经加载)。由于某种原因,该代码无法正常工作。以下是代码示例:
$(function(){
$('body')
.append('<form id="mySearch"></form>'); //append a new form element with id mySearch to <body>
$('#mySearch')
.attr("action","mySearchPage.cfm") .attr("method","post") //set the form attributes
//add in all the needed input elements
.append('<input type="hidden" name="btnSearch" id="btnSearch" value="Search">')
.append('<input type="hidden" name="txtField1" id="txtField1" value="">')
.append('<input type="hidden" name="txtField2" id="txtField2" value="">')
.append('<input type="hidden" name="selType" id="selType" value="0">')
.append('<input type="hidden" name="selType2" id="selType2" value="2">')
});
表单未插入到页面正文中。我做错了什么?
更新:我发现当我在自己的页面中使用代码时,它可以正常工作。当我尝试将其集成到一个大型的现有页面中时,它不再起作用。关于什么可能导致完全相同的代码失败的任何想法?
I'm using jquery to insert a hidden form into a page (once the page has already loaded). For some reason the code is not working. Here is a sample of the code:
$(function(){
$('body')
.append('<form id="mySearch"></form>'); //append a new form element with id mySearch to <body>
$('#mySearch')
.attr("action","mySearchPage.cfm") .attr("method","post") //set the form attributes
//add in all the needed input elements
.append('<input type="hidden" name="btnSearch" id="btnSearch" value="Search">')
.append('<input type="hidden" name="txtField1" id="txtField1" value="">')
.append('<input type="hidden" name="txtField2" id="txtField2" value="">')
.append('<input type="hidden" name="selType" id="selType" value="0">')
.append('<input type="hidden" name="selType2" id="selType2" value="2">')
});
The form is not being inserted into the body of the page. What am I doing wrong?
Update: I've found that when I use the code in a page on it's own it works correctly. When I try to integrate it into a large, already existing page it no longer works. Any ideas about what might cause the exact same code to fail?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
无论如何,你绝对应该避免这种向 dom 添加动态内容的方法。
最好的技术是创建一个包含所有必要标记的单个字符串,并将其一次性注入!像这样的东西:
try this:
Anyway you should absolutely avoid this kind of approach to add dynamic content to the dom.
The best technique is to create a single string containing all the necessary markup and inject it in one shot! Something like:
它对我有用,也许您不想要隐藏的表单字段?
http://jsfiddle.net/M5vWR/
查看此带有可见表单元素的内容。
http://jsfiddle.net/M5vWR/2/
It works for me, perhaps you don't want hidden form fields?
http://jsfiddle.net/M5vWR/
See this one with visible form elements.
http://jsfiddle.net/M5vWR/2/
毕竟,这只是文件中包含 javascript 的额外标记的语法问题:P 代码现在可以运行了!
After all, it was just a syntax problem with an extra tag in the file that included the javascript :P The code works now!