【发布时间】:2017-06-02 12:46:14
【问题描述】:
我遇到需要将子 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 html