【问题标题】:Add inline style using Javascript to divs created dynamically使用 Javascript 将内联样式添加到动态创建的 div
【发布时间】:2014-09-27 16:19:22
【问题描述】:

我正在使用 javascript 创建动态 div。我想将样式分配给 none。

style="display: none;"

根据这个question,我可以使用以下选项来做到这一点

 publishcontent.style.display="none";
 publishcontent.setAttribute("style", "display: none;");

但这不起作用。这就是我创建 div 的方式。我发现的任何选项都不起作用。如果我用 firebug 编辑 html 并输入 style="display: none;" 它可以工作。

这是显示示例的demo

publishpaging=document.createElement("div");
var name="df"+counterName;
publishpaging.id=name;
counterName=counterName+1;
arrayNames.push(name);
counter++;
publishcontent=document.createElement("div");//"<div class='bonecardSmall'></div>";
publishcontent.className = "bonecardSmallP";
publishcontent.id=index.id;
if(arrayNames.length > 1){
    //publishpaging.style.display="none";
    publishpaging.setAttribute("style", "display: none;");
}
publishpaging.appendChild(publishcontent);

【问题讨论】:

  • 你确定if条件为真
  • 是的,它在一个for里面,有显示循环的jsbin
  • 我想你想检查 arrayNames.length &gt; 0 你的 jsbin 显示 arrayNames.length 是 1。所以这个条件不成立。
  • 我有一个从 0 到 12 的循环。每次执行 arrayNames.push(name) 时,第一次迭代后的长度都会大于 1。这不是问题
  • 你只是想隐藏它? jsbin.com/yibeqoqa/1/edit

标签: javascript jquery html css


【解决方案1】:

“name”变量存储publishcontent的id,所以在jquery中使用

 $('#'+name).css('display','none');

【讨论】:

  • OP已经有元素的引用为publishpaging,所以可以直接设置属性。 jQuery 至少应该是$(publishpaging).css('display','none')。但是,这非常低效,publishcontent.style.display = 'none' 没有理由不工作。
【解决方案2】:

使用 jQuery,只需使用:

$('div').css('display','none');

【讨论】:

  • 它不起作用 $(publishcontent).css('display','none');
  • @Diego 新添加的 div 附加在哪里?父元素的id或类是什么?
【解决方案3】:

用jquery试试这个,

$('yourdivtagid').css('display','none')

【讨论】:

  • 不,他刚刚提到了 $('div')。我认为他应该使用 div 标签 id。
【解决方案4】:

您可以简单地使用 jquery 隐藏功能隐藏。

$("#"+ name).hide();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 2017-06-05
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 2013-10-24
    • 1970-01-01
    相关资源
    最近更新 更多