正如标题所说,如果其中一个属性具有特定值,我需要更改新对象的样式。我不能通过定义具有样式的另一个属性来做到这一点,虽然我大致知道我正在查看的属性和值的特征(将是正则表达式),但是对象将在某些时候从外部json文件动态创建(尚未达到那个部分)。
但是,当我尝试在构造函数的display方法中使用if语句时,基于该构造函数创建的所有对象的样式采用最后定义的样式。
我正在处理的系统不支持任何类型的框架,因此jquery解决方案将无法使用。
代码(我简化了此问题的代码)
function standardBook(title, author, category, coverType) {
this.title = title || "unknown title";
this.author = author || "unknown author";
this.category = category || "unknown category";
this.coverType = coverType || "unknown cover type";
this.display = function() {
if (this.title == "Harry Potter") {
msg.innerHTML += "<li> yet another harry potter book </li>" //just used this as an example to see if the statement works
msg.style.color = "red"; //style change no. 1
} else {
msg.innerHTML += "<li>" + this.title + " - " + this.author + ", " + this.category + ", " + this.coverType + "</li>";
msg.style.color = "black"; //style for the rest of the items. If i remove it, all items will be red. If I keep it here, all are black;
};
}
};
var book1 = new standardBook("Harry Potter", "JK Rowling", "fantasy", "hard cover");
var book2 = new standardBook("Lord of The Rings", "JR Tolkien", "fantasy", "ebook");
book1.display();
book2.display();
<ul id="msg"></ul>
答案 0 :(得分:0)
您正在为ul分配样式而不是新创建的li元素。请为li节点设置样式。对不起从手机上回答的拼写错误。