使用数组创建Div Dom元素

时间:2018-06-26 09:39:09

标签: javascript jquery html arrays

我下面的代码中有一个Multidimensional Array,我正在使用此array动态创建DOM elements来填充我的HTML Tab,现在的问题是我我试图使用我的['hobbyies']数组将其附加到tab中每个名称的下面。

我使用了foreach循环,使每个[hobbies]数组值都有自己的div标签。但是我不确定如何使用每个div将其附加在名称下方。任何建议将不胜感激。 enter image description here

var personArr = [];
var person = {["first-Name"]: "John", ["last-Name"]: "Doe", ["age"]: 21, ["hobbies"]:["football","swimming","dancing"],
  ["person-desc"]: "<br />Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky <br />boudin picanha shankle turducken prosciutto cow kielbasa tenderloin."
};
var person2 = {
  ["first-Name"]: "Paul",
  ["last-Name"]: "Logan",
  ["age"]: 22,
  ["hobbies"]:["camping","sleeping","eating"],
  ["person-desc"]: "Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin. "
};
var person3 = {
  ["first-Name"]: "Sean",
  ["last-Name"]: "Kim",
  ["age"]: 32,
  ["hobbies"]:["running","jogging","climbing"],
  ["person-desc"]: "Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin."
};
var person4 = {
  ["first-Name"]: "Ken",
  ["last-Name"]: "Chow",
  ["age"]: 12,
  ["hobbies"]:["gyming","movies","tv"],
  ["person-desc"]: "Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin."
};

personArr.push(person, person2, person3, person4);
console.log(personArr);
var $parent = $('.line1').eq(0);



personArr.forEach((person, i) => {
  var $name = $('<h4/>');
  var $desc = $('<p/>');
  var $hobbie = $('<div/>');
	
	
  var hobbieArray = '';
	$.each(person['hobbies'], function (index) {
    hobbieArray += ('<div class="hobclass ">' + person['hobbies'][index] + '</div>');
	});
  
  $name.html(` ${person['first-Name']} ${person['last-Name']}`);
  $desc.html(` ${person['person-desc']}`);
  $parent.append($name).append($desc).append($hobbie);

});


//<---------------------------------------------- TAB FUNCTION ------------------------------------------------------->
function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}
document.getElementById("defaultOpen").click();
body {font-family: Arial;}

/* Style the tab */
.tab {
    overflow: hidden;
    border: 1px solid #ccc;
    background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
    background-color: inherit;
    float: left;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 14px 16px;
    transition: 0.3s;
    font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
    background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
    background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
    display: none;
    padding: 6px 12px;
    border: 1px solid #ccc;
    border-top: none;
}
.line1{
display:inline-block;
}
.size{
width:50%;
}
a.morelink {
	text-decoration:none;
	outline: none;
}
.morecontent span {
	display: none;

}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

</head>
<body>
<div class ="size">
<div class="tab">
  <button class="tablinks" onclick="openCity(event, 'People')" id="defaultOpen">People</button>
</div>

<div id="People" class="tabcontent">
<div class="line1"> 

 </div>
 </div>
</div>

</body>
</html> 

3 个答案:

答案 0 :(得分:2)

您只需要在hobbieArray元素中插入$hobbie(这是HTML字符串,而不是数组)。像在其他地方一样使用.html

var hobbieHTML = '';
$.each(person['hobbies'], function (index) {
    hobbieHTML += ('<div class="hobclass ">' + person['hobbies'][index] + '</div>');
});
$hobbie.html( hobbieHTML );

使用JS编写HTML有点笨拙,使用元素通常更容易(例如您已经使用过$name$desc

$.each(person['hobbies'], function (index) {
    var $h = $('<div/>').addClass('hobclass').text( person['hobbies'][index] );
    $hobbie.append( $h );
});

定义对象键时,您无需同时使用[]""。键只有特殊字符时,才需要""。如果可以的话,通常最好不要使用特殊字符来命名密钥。

var person2 = {
    firstName: "Paul",
    lastName: "Logan",
    age: 22,
    hobbies: [ "camping", "sleeping", "eating" ],
    description: "Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin. "
};

现在,使用点符号访问对象的属性更加容易。您还可以使用本机Array.forEach代替jQuery的$.each

person.hobbies.forEach( function ( hobby ) {
    var $h = $('<div/>').addClass('hobclass').text( hobby );
    $hobbie.append( $h );
})
$name.html(` ${ person.firstName } ${ person.lastName }`);
$desc.html(` ${ person.description }`);

答案 1 :(得分:1)

您的代码$hobbie中的

没有内容可显示。您正在使用hobbiearray构建div,我已经更新了您的代码,这就是您想要的吗?

更新的代码段

var $hobbieArray = '<div>';
        $.each(person['hobbies'], function (index) {
        $hobbieArray += ('<div class="hobclass ">' + person['hobbies'][index] + '</div>');
        });
$hobbieArray += '</div>'

var personArr = [];
var person = {["first-Name"]: "John", ["last-Name"]: "Doe", ["age"]: 21, ["hobbies"]:["football","swimming","dancing"],
  ["person-desc"]: "<br />Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky <br />boudin picanha shankle turducken prosciutto cow kielbasa tenderloin."
};
var person2 = {
  ["first-Name"]: "Paul",
  ["last-Name"]: "Logan",
  ["age"]: 22,
  ["hobbies"]:["camping","sleeping","eating"],
  ["person-desc"]: "Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin. "
};
var person3 = {
  ["first-Name"]: "Sean",
  ["last-Name"]: "Kim",
  ["age"]: 32,
  ["hobbies"]:["running","jogging","climbing"],
  ["person-desc"]: "Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin."
};
var person4 = {
  ["first-Name"]: "Ken",
  ["last-Name"]: "Chow",
  ["age"]: 12,
  ["hobbies"]:["gyming","movies","tv"],
  ["person-desc"]: "Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin."
};

personArr.push(person, person2, person3, person4);
console.log(personArr);
var $parent = $('.line1').eq(0);



personArr.forEach((person, i) => {
  var $name = $('<h4/>');
  var $desc = $('<p/>');
  var $hobbie = $('<div/>');
	
	
  var $hobbieArray = '<div class="root-div">';
	$.each(person['hobbies'], function (index) {
    $hobbieArray += ('<div class="hobclass ">' + person['hobbies'][index] + '</div>');
	});
$hobbieArray += '</div>'
  
  $name.html(` ${person['first-Name']} ${person['last-Name']}`);
  $desc.html(` ${person['person-desc']}`);
  $parent.append($name).append($desc).append($hobbieArray);

});


//<---------------------------------------------- TAB FUNCTION ------------------------------------------------------->
function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}
document.getElementById("defaultOpen").click();
body {font-family: Arial;}

/* Style the tab */
.tab {
    overflow: hidden;
    border: 1px solid #ccc;
    background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
    background-color: inherit;
    float: left;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 14px 16px;
    transition: 0.3s;
    font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
    background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
    background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
    display: none;
    padding: 6px 12px;
    border: 1px solid #ccc;
    border-top: none;
}
.line1{
display:inline-block;
}
.size{
width:50%;
}
a.morelink {
	text-decoration:none;
	outline: none;
}
.morecontent span {
	display: none;

}
.root-div {
background-color: yellow
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

</head>
<body>
<div class ="size">
<div class="tab">
  <button class="tablinks" onclick="openCity(event, 'People')" id="defaultOpen">People test</button>
</div>

<div id="People" class="tabcontent">
<div class="line1"> 

 </div>
 </div>
</div>

</body>
</html> 

答案 2 :(得分:1)

var hobbieArray = '';的声明移动到循环之前的某个位置,然后以与对namedesc进行操作的相同方式将其附加到

var personArr = [];
var person = {["first-Name"]: "John", ["last-Name"]: "Doe", ["age"]: 21, ["hobbies"]:["football","swimming","dancing"],
  ["person-desc"]: "<br />Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky <br />boudin picanha shankle turducken prosciutto cow kielbasa tenderloin."
};
var person2 = {
  ["first-Name"]: "Paul",
  ["last-Name"]: "Logan",
  ["age"]: 22,
  ["hobbies"]:["camping","sleeping","eating"],
  ["person-desc"]: "Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin. "
};
var person3 = {
  ["first-Name"]: "Sean",
  ["last-Name"]: "Kim",
  ["age"]: 32,
  ["hobbies"]:["running","jogging","climbing"],
  ["person-desc"]: "Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin."
};
var person4 = {
  ["first-Name"]: "Ken",
  ["last-Name"]: "Chow",
  ["age"]: 12,
  ["hobbies"]:["gyming","movies","tv"],
  ["person-desc"]: "Bacon ipsum dolor amet short loin doner tail meatloaf hamburger jerky boudin picanha shankle turducken prosciutto cow kielbasa tenderloin."
};

personArr.push(person, person2, person3, person4);
console.log(personArr);
var $parent = $('.line1').eq(0);


 var hobbieArray = '';

personArr.forEach((person, i) => {
  var $name = $('<h4/>');
  var $desc = $('<p/>');
  var $hobbie = $('<div/>');
	
	
      	$.each(person['hobbies'], function (index) {
    hobbieArray += ('<div class="hobclass ">' + person['hobbies'][index] + '</div>');
	});
  
  $name.html(` ${person['first-Name']} ${person['last-Name']}`);
  $desc.html(` ${person['person-desc']}`);
  $hobbie.html(hobbieArray)
  $parent.append($name).append($desc).append($hobbie);

});


//<---------------------------------------------- TAB FUNCTION ------------------------------------------------------->
function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}
document.getElementById("defaultOpen").click();
body {font-family: Arial;}

/* Style the tab */
.tab {
    overflow: hidden;
    border: 1px solid #ccc;
    background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
    background-color: inherit;
    float: left;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 14px 16px;
    transition: 0.3s;
    font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
    background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
    background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
    display: none;
    padding: 6px 12px;
    border: 1px solid #ccc;
    border-top: none;
}
.line1{
display:inline-block;
}
.size{
width:50%;
}
a.morelink {
	text-decoration:none;
	outline: none;
}
.morecontent span {
	display: none;

}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

</head>
<body>
<div class ="size">
<div class="tab">
  <button class="tablinks" onclick="openCity(event, 'People')" id="defaultOpen">People</button>
</div>

<div id="People" class="tabcontent">
<div class="line1"> 

 </div>
 </div>
</div>

</body>
</html>