所以我这里有问题。我给几个div设置了一些自定义样式,让它们暂时不可见。但是,当我使用文档写入功能从外部 .js 文件生成文本时,这些自定义样式似乎不会触发:
CSS:
<style type="text/css">
.section
{
display: none;
}
.section#form1
{
display: block;
}
用于切换可见性的 JavaScript 函数:
function toggleVisibility(newSection)
{
$(".section").not("#" + newSection).hide();
$("#" + newSection).show();
}
在生成此页面上大部分内容的递归循环函数中的某处,我有这个
...
if (step != 1)
{
document.write("</div>");
}
document.write("<div id='form"+step+"' class='section'>");
...
我是否需要某种代码来指定 JavaScript 将表单的所有元素打印到某个外部 div 的位置?我似乎无法理解为什么所有的 div 在开始时都是可见的,我之前做了相同的代码并且它工作得很好。也许 document.write 的一个很好的替代品可能会达到目的。感觉 document.write 有点覆盖一切。
$(document).ready(function()
{
$('#show-results').click(function()
{
$.post('JSAAN.php', function(data)
{
var pushedData = jQuery.parseJSON(data);
// Uses the function from loop.js
document.write("<form id='evalForm' onsubmit='return false;'>");
var fieldsetActive = 0;
loop(pushedData);
})
})
});
循环函数(在单独的文件中是这样开始的:
function loop(obj) {
// Starts the form
$.each(obj, function(key, val) {
if($.isPlainObject(val) || $.isArray(val)) { // object, call recursively
最佳答案
不要使用 document.write
来创建您的 div
,请考虑使用 document.createElement
。
var elem = document.createElement('div'),
formStep = 'form' + step;
elem.setAttribute('id', formStep);
elem.setAttribute('class', 'section');
这会将元素插入到 DOM 中。 document.write
不推荐用于此类用法。
如果需要使用jQuery:
// using document.createElements('div') as the selector is the fastest way
var elem = $(document.createElement('div')),
formStep = 'form' + step;
elem.attr('id', formStep).attr('class', 'section');
如果您有任何问题,请告诉我。
关于javascript - CSS 不适用于 Javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11524136/