![](/img/trans.png)
[英]Child div elements not appearing in parent div element created by JavaScript function
[英]Add Child Element to Parent on a Set of Matched Elements, and use Parent Div href - Javascript
我有一種情況,我需要將一個子div附加到一組元素。 子元素是一個div,它具有一個從其父元素獲取href的錨鏈接。
當我最初只使用一個div時,這一切都很簡單,但是現在我正試圖讓它在一組具有CSS類選擇器的元素上工作我似乎只是繞着圓圈轉而且它正在變得越來越很沮喪:(
這是一個codepen鏈接: https ://codepen.io/emilychews/pen/XgrqWZ
這是它應該看起來的第二個codepen(這個例子只有一個父元素): https ://codepen.io/emilychews/pen/RgbawK
我剛剛遇到的另一個問題是,當有許多實例使用同一個類時,我如何擁有它以便每個子元素始終采用來自父元素的href?
任何幫助都會很棒。 艾米麗。
HTML
<div class="outerbox">
<a href="https://www.google.co.uk">Here is a job Title</a>
</div>
<div class="outerbox">
<a href="https://www.bbc.co.uk">Here is a job Title</a>
</div>
CSS
* {font-family: arial; color: white;}
body {display: flex; justify-content: space-around;}
.outerbox {
display: flex;
justify-content: center;
align-items: center;
width: 250px;
height: 200px;
background: red;
position: relative;
padding: 20px;
box-sizing: border-box;
}
.outerbox a {margin-right: auto; margin-bottom: auto;}
.innerbox {
background: blue;
position: absolute;
padding: 15px 30px;
}
.innerbox a { text-decoration: none;}
JS
// DECLARE OUTERBOX
var outerbox = document.querySelectorAll('.outerbox');
// GET PARENT ELEMENT HREF ATTRIBUTE
var parentLink = document.querySelectorAll('.outerbox a');
for (var i = 0; i < parentLink.length; i+=1) {
var innerHREF = parentLink[i].getAttribute("href");
}
// CREATE INNERBOX
var innerBox = document.createElement('div');
innerBox.classList = "innerbox";
// CREATE ANCHOR LINK AND PASS IN HREF VAR
var anchorTag = document.createElement('a');
anchorTag.setAttribute("href", innerHREF); // pass in innerHREF var
anchorTag.appendChild(innerHREF);
anchorTag.innerHTML = "Apply";
for (var j = 0; j = innerbox.length; j+=1) {
innerbox[j].appendChild(anchorTag)
}
// ADD INNERBOX TO OUTERBOX
outerbox.appendChild(innerBox);
你的javascript有一些錯誤,試試這個
<script>
document.querySelectorAll('.outerbox').forEach(function(element){
//get parent link
//var innerHREF=element.querySelector('a').href;
//you need no var, i put it direct on line marked with //*****
//create innerBox
var innerBox = document.createElement('div');
innerBox.classList.add('innerbox');
// CREATE ANCHOR LINK AND PASS IN HREF VAR
var anchorTag = document.createElement('a');
anchorTag.setAttribute("href", element.querySelector('a').href); //***
anchorTag.innerHTML = "Apply";
innerBox.appendChild(anchorTag);
element.appendChild(innerBox);
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.