JavaScript从对象动态添加多个属性

时间:2019-07-04 03:41:30

标签: javascript html forms loops dynamic

我创建了一个对象,并带有要添加到html标签的属性列表。我想将它们添加到创建的元素中。 这是代码

  

var up = {class:“ upt”,名称:“ positive_use”,类型:“ text”};

     

createtextarea = document.createElement(“ TEXTAREA”);

如何将这些对象添加到元素中。 以及如何动态添加多个。

2 个答案:

答案 0 :(得分:1)

您可以像这样使用setAttribute

var up={class:"upt", name:"positive_use",type:"text"};

let createtextarea = document.createElement('TEXTAREA');

createtextarea.setAttribute('class', up.class);
createtextarea.innerHTML = "TEST TEXT AREA";
createtextarea.setAttribute('name', up.name);
createtextarea.setAttribute('type', up.type);

document.body.appendChild(createtextarea);

答案 1 :(得分:0)

您可以在up的对象键上运行一个foreach循环,然后使用setAttribute函数。

#Create sample dataframe
df <- data.frame("x_pos" = c("A","A","A","B","B","B","C","C","C"),
                 "y_pos" = c("X","Y","Z","X","Y","Z","X","Y","Z"),
                 "col_var"= c(1,2,NA,4,5,6,NA,8,9),
                 "alpha_var" = c(7,12,0,3,2,15,0,6,15))

#Convert factor columns to numeric
df$col_var<- as.numeric(df$col_var)
df$alpha_var<- as.numeric(df$alpha_var)

#Cut display variable into breaks
df$col_var_cut <- cut(df$col_var,
                         breaks = c(0,3,6,10),
                         labels = c("cat1","cat2", "cat3"))
#Plot
library(ggplot2)                
ggplot(df, aes (x = x_pos, y = y_pos, fill = col_var_cut, label = col_var)) +
  geom_tile () +
  geom_text() +
  scale_fill_manual(values=(brewer.pal(3, "RdYlBu")),na.value="white") +
  geom_tile(aes(alpha = alpha_var), fill ="gray29")+
  scale_alpha_continuous("alpha_var", range=c(0,0.7), trans = 'reverse')+
  theme_bw() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1))