【问题标题】:Why is my innerHTML is overwriting style properties of the parent class? and how do i solve this?为什么我的 innerHTML 会覆盖父类的样式属性?我该如何解决这个问题?
【发布时间】:2013-07-25 13:01:18
【问题描述】:

我是 Aron,我是 javascript 的新手

这是我的问题:

我正在尝试从我的 html 中的表单输入创建新内容 但是如果你在表单中输入了很多字符,新的 html 不会以正确的宽度分解。

我希望我正确地解释了这一点。这是我的site的链接

这是我的 javascript:

function plaatsMagnet()
    {

        console.log('plaatsMagnet');

        $('#magnetcontent').prepend('<div id="magnetjes" class="large-3 columns"></div>');

        var textmagnet = $('#textMagnet').val()
        var naammagnet = $('#inhoud').val()



        var 

        divTag = document.createElement("div");

        divTag.id = "magnetje";

              divTag.className =" panel";

              divTag.innerHTML =   "<h5>" + (naammagnet) + "</h5>" + "<p>" + (textmagnet) + "</p>";

        $('#magnetjes').append(divTag);


    };

我真的希望你们能帮助我! :)

【问题讨论】:

  • 为什么要给所有 div 的 id 相同?
  • 嗨 Amogh Talpallikar,因为我不知道如何使用 javascript 创建不同的 div。你会怎么做?
  • 我用你的代码更新了 tester2。我把所有的脚本都放在了头上,我将下面的函数粘贴到了正文中,现在它可以工作了。每个创建的 div 都是独一无二的。 非常感谢!
  • 现在我希望解决为什么新的 html 不能在正确的宽度上分解的问题。你知道是什么导致了这个 Amogh Talpallikar 吗?
  • 为 div 提供固定宽度。你做到了吗?

标签: javascript html dom styles innerhtml


【解决方案1】:
 jesCount = 0; // will keep the counter for magnetjes divs
 jeCount = 0; // will keep the counter for magnetje divs 

 // All the ids will be unique, magnetjes0,magnetjes1.... and magnetje0, magnetje1...
// if you can mantain an array instead it will be better.
// I have taken counters as global vars to show different id implementations for each div. I deally you should encapsulate such change in a function.

function plaatsMagnet()
{

    console.log('plaatsMagnet');

    $('#magnetcontent').prepend('<div id="magnetjes'+ jesCount +'" class="large-3 columns"></div>');

    var textmagnet = $('#textMagnet').val()
    var naammagnet = $('#inhoud').val()



    var 

    divTag = document.createElement("div");

    divTag.id = "magnetje" + jeCount; // will increment the current value and 
          jeCount++;
          divTag.className =" panel";

          divTag.innerHTML =   "<h5>" + (naammagnet) + "</h5>" + "<p>" + (textmagnet) + "</p>";

    $('#magnetjes'+jesCount).append(divTag);
     jesCount++;


};

【讨论】:

  • Amogh,非常感谢! :) 我复制了您的代码,但是当我运行 javascript 时,没有创建任何内容。我应该在哪里放置:jesCount = 0; jeCount = 0; ?它现在在我的文档准备功能中
  • 只要确保这些是全局的并在调用 plaatsMagnet 之前声明。基本上你的身份证名称应该不同。并且该计数器将是名称中的后缀。
  • 好的,成功了,我又试了一次。它似乎不起作用?我将它上传到aronmartin.com/tester2,因为您可以看到没有创建任何内容。
  • 我现在明白了一点.. 我正在努力让它工作!也许字符串中的某处有错误? '
    ');也许现在它这样说:
    jesCount class="large-3 columns">
    ?
  • 是的。它应该是。 '
    ' 双引号应该在我们添加后,jesCount。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-04
  • 2018-01-28
  • 1970-01-01
  • 1970-01-01
  • 2015-06-13
  • 1970-01-01
相关资源
最近更新 更多