从班级中删除一个div

时间:2019-05-14 12:11:28

标签: javascript html

我目前正在使用Javascript和HTML,并且有多个具有相同类的div标签。

<div class="box"> Hello </div>
<div class="box"> How are you? </div>
<div class="box"> Goodbye </div>
<div class="box"> Who are you? </div>

然后我为每个DIV贴了一个标签:

<a> Click me </a>

所以会是这样:

<div class="box"> Hello </div>
<a> Click me </a>

<div class="box"> How are you? </div>
<a> Click me </a>

<div class="box"> Goodbye </div>
<a> Click me </a>

<div class="box"> Who are you? </div>
<a> Click me </a>

我的问题是:如果单击div标签,如何获得div的值? (使用Javascript)

4 个答案:

答案 0 :(得分:1)

您可以像这样使用previousElementSibling

function clickATag(){
   let sib = this.previousElementSibling;
   sib.style.border = "1px solid red"
   console.log(sib.innerText);
}

function clickATag(){
   let sib = this.previousElementSibling;
   sib.style.border = "1px solid red";
   console.log(sib.innerText)
  
}

Array.prototype.forEach.call(
    document.querySelectorAll('a'), 
    function (element) {
        element.addEventListener('click', clickATag, false);
    }
);
<div class="box"> Hello </div>
<a> Click me </a>

<div class="box"> How are you? </div>
<a> Click me </a>

<div class="box"> Goodbye </div>
<a> Click me </a>

<div class="box"> Who are you? </div>
<a> Click me </a>

答案 1 :(得分:0)

您可以在此处编写简单的jquery代码:

$('a').click(function(){
  alert($(this).prev().text());
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box"> Hello </div>
<a> Click me </a>

<div class="box"> How are you? </div>
<a> Click me </a>

<div class="box"> Goodbye </div>
<a> Click me </a>

<div class="box"> Who are you? </div>
<a> Click me </a>

答案 2 :(得分:0)

感谢Andreas。我不知道.previousElementSibling

var getValueOfDiv = void 0;
{
    getValueOfDiv = function () {
        console.log(this.previousElementSibling.innerHTML);
        return false;
    }
}
Array.prototype.forEach.call(
    document.querySelectorAll('a'), 
    function (element) {
        element.addEventListener('click', getValueOfDiv, false);
    }
);

答案 3 :(得分:0)

您想做的事情不是正确的方法。可能是您想要执行的操作

var link = document.getElementById('abc');
       abc.addEventListener('click',function(e){
           if(e.target.tagName.toLowerCase() === 'a'){
               
             console.log(e.target.previousSibling.previousSibling.innerHTML);
            }
        
          
       });
<div id="abc">
            <div class="box"> Hello </div>
            <a> Click me </a>
            
            <div class="box"> How are you? </div>
            <a> Click me </a>
            
            <div class="box"> Goodbye </div>
            <a> Click me </a>
            
            <div class="box"> Who are you? </div>
            <a> Click me </a>
    </div>