2017-05-28 102 views
0

如标题所示,如果其中一个属性具有特定值,则需要更改新对象的样式。我不能通过定义具有样式的另一个属性来做到这一点,虽然我大致知道我正在查看的属性和值的特征(将是正则表达式),但是对象将在某个时刻从外部json文件动态创建(还没有到那个部分)。Javascript - 为特定属性值更改对象的显示样式

但是,当我尝试在构造函数的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>

+1

当然,如果您为列表本身指定颜色,所有列表项目将具有相同的颜色。你想为特定的列表项目指定它。 – CBroe

+0

你是完全正确的。出于某种原因,我一直在这个不必要的复杂 –

回答

0

您指定的风格UL,而不是新创建的li元素。请为li节点设置样式。抱歉从手机接收到错别字。

+0

这真的应该是一个评论,而不是一个答案 –

+0

谢谢你,你是对的。 –