【问题标题】:Dynamically creating div and element created add style动态创建 div 和元素创建添加样式
【发布时间】:2016-10-15 19:09:30
【问题描述】:

动态创建 div 和创建元素添加样式

var div = document.createElement('div');
div.setAttribute("id","div1");
document.body.appendChild(div);
//above simulation dynamic ajax loading

$(document).ready(function () {
    $(document).on('load','#div1',function () {
        console.log(12323);
        $(this).css({'color':'red'});
    });
});

它不起作用;控制台为空白;颜色不是红色;帮帮我;

【问题讨论】:

  • $(document).on('load','#div1',function () {
  • Div 正在使用 jquery 或通过服务器端脚本创建

标签: javascript jquery


【解决方案1】:

不需要load()

   var div = document.createElement('div');
   div.setAttribute("id", "div1");
   document.body.appendChild(div);
    //above simulation dynamic ajax loading

   $(document).ready(function() {
     $('#div1').css({
       'color': 'red',
       'width': '100px',
       'height': '100px',
       'background': 'yellow'
     });
   });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【讨论】:

    【解决方案2】:

    试试这个...

    jQuery load() 方法从服务器加载数据并将返回的数据放入所选元素中。

    onload 事件必须使用ready()

    var div = document.createElement('div');
    div.setAttribute("id", "div1");
    document.body.appendChild(div);
    //above simulation dynamic ajax loading
    
    $(document).ready(function() {
      $(div).ready(function() {
        console.log(12323);
        $(div).css({
          'color': 'white',
          'background': 'red',
          'height': '200px',
          'width': '200px'
        });
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

    【讨论】:

    • 其实所有的li'elements都来自一个服务器,等待数据响应前,我想要第一个元素的样式颜色是红色的!你的答案运行正常,但 'div' 变量句柄没有被捕获。
    • 对不起,我的英语很糟糕,所以我描述不清楚。
    【解决方案3】:

    这是你想要完成的吗?

    $(document).ready(function(){
      $('body').append('<div id="div1">Hi</div>');
      $('#div1').css({'color':'red'});
      console.log('12323');
    });
    &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

    【讨论】:

      【解决方案4】:

      实现它的更有效和DRY 的方法是:

      function createElement(elem, attr, parent){
        "use strict";
        var dom = document,
        el = dom.createElement(elem);
        if(attr.id > ''){
          el.id = attr.id;
        } if(attr.class > ''){
          el.className += attr.class;
        }
        if (parent > '') {
          parent.appendChild(el);
        } else {
          dom.body.appendChild(el);
        }
      }
      
      var div1 = document.getElementById("div1");
      createElement("div", {id: "test1", class: "test2"}, div1);
      

      【讨论】:

        猜你喜欢
        • 2021-11-10
        • 2012-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-08
        • 1970-01-01
        • 1970-01-01
        • 2014-01-25
        相关资源
        最近更新 更多