2017-06-02 46 views
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); 

回答

0

你的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> 
+0

['nodeList.forEach()'](https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach)。 –

+0

这是正确的。 IE不知道'nodeList.forEach',但也不知道Array.forEach。我知道'[] .forEach.call(document.querySelectorAll('。outerbox'),function(element){' –

+0

我已经改变了代码,谢谢。 –

相关问题