[英]Creating a HTMLdivElement object in Javascript
尝试将String转换为HTMLDivElement对象。 我知道如何创建字符串,只是不确定如何创建HTMLDivElement。
例如,如果我想将<div id="cardId" class="card c9"></div>
真正了解HTMLDivElementObject也是一件好事。
编辑:
我也知道有通用属性,例如id(string),style(object),title(string)和className(string)。
下面是我的功能和方法。 如您所见,我尝试创建toElement
方法。 我需要的是返回代表Card的HTMLDivElement对象的方法。 需要返回的示例如上述<div id="cardId" class="card c9"></div>
。
var cardProto = {
// creates the HTML string representing this element
"toString": function (){
var s = this.card.getSuit(), r = this.card.getRank();
var t = "<div class=\"card ";
t += s !== undefined ? s + r : "down";
t += "\" id=\""+ this.id + "\"></div>\n";
return t;
},
"toElement": function () {
}
};
"toElement": function () {
var dummy = document.createElement("div");
dummy.innerHTML = this.toString();
return dummy.children[0];
}
弄清楚了伙计们。 要设置ID,我需要为该类使用.id和.className。
"toElement": function () {
var s = this.card.getSuit(), r = this.card.getRank();
var div = document.createElement('div');
div.id = 'cardId';
div.className = "card " +s+r;
return div;
}
假设您要将字符串转换为元素,可以使用RegEx来执行此操作:
"toElement": function () {
var string = '<div id="cardId" class="card c9"></div>'
var e = /<(.+?)\s/g.exec(string)[1];
var id = /id="(.+?)"/g.exec(string)[1];
var cls = /class="(.+?)"/g.exec(string)[1];
var element = document.createElement(e);
element.hash = id;
element.className = cls;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.