3
我有一種情況,需要將一個子div附加到一組元素中。子元素是一個具有錨鏈接的div,從其父元素獲取href。在一組匹配元素上添加子元素到父項,並使用Parent Div href - Javascript
當我這樣做最初只使用一個div它足夠簡單,但現在我試圖讓它在一組CSS元素選擇器上工作我似乎只是在一輪圓圈和它變得非常沮喪:(
這裏是一個codepen鏈接:https://codepen.io/emilychews/pen/XgrqWZ
這裏是第二codepen它應該如何看(這個例子中只有一個父元素):https://codepen.io/emilychews/pen/RgbawK
另一個問題剛剛發生在我身上的是,我如何擁有它,以便每個孩子el當存在多個使用相同類的實例時,總是需要從父元素中獲取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);
['nodeList.forEach()'](https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach)。 –
這是正確的。 IE不知道'nodeList.forEach',但也不知道Array.forEach。我知道'[] .forEach.call(document.querySelectorAll('。outerbox'),function(element){' –
我已經改變了代碼,謝謝。 –