[英]Dynamically creating div and element created add style
動態創建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'});
});
});
這是行不通的; 控制台為空; 顏色不是紅色; 幫我;
不需要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>
嘗試這個...
jQuery load()
方法從服務器加載數據,並將返回的數據放入選定的元素。
您必須將ready()
用於onload事件
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>
這是您要完成的工作嗎?
$(document).ready(function(){ $('body').append('<div id="div1">Hi</div>'); $('#div1').css({'color':'red'}); console.log('12323'); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
一種更有效且更干燥的方法是:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.