单击事件查找下一个div以添加一个css类Typescript

时间:2016-06-08 20:39:11

标签: javascript typescript

我想在Typescript中创建一个函数来查找下一个div并添加一个css类,这是我的尝试:

<ul>
    <li><a href="#" onclick="toggle()">Item 1</a></li>
    <div class="content hide"></div>
    <li><a href="#" onclick="toggle()">Item 2</a></li>
    <div class="content hide"></div>
    <li><a href="#" onclick="toggle()">Item 3</a></li>
    <div class="content hide"></div>
    <li><a href="#" onclick="toggle()">Item 4</a></li>
    <div class="content hide"></div>
    <li><a href="#" onclick="toggle()">Item 5</a></li>
    <div class="content hide"></div>
</ul>

现在是Typescript中的函数

function toggle(){
   this.parent().next('.content').class('hide');
}

谢谢你们

2 个答案:

答案 0 :(得分:0)

  

this不是你所假设的!您可以将当前元素作为参数传递给this

另请注意,没有.class方法,您应该使用.toggleClass方法。

function toggle(elem) {
  $(elem).parent().next('.content').toggleClass('hide');
}
.hide {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<ul>
  <li><a href="#" onclick="toggle(this)">Item 1</a>
  </li>
  <div class="content hide">Content Goes here!</div>
  <li><a href="#" onclick="toggle(this)">Item 2</a>
  </li>
  <div class="content hide">Content Goes here!</div>
  <li><a href="#" onclick="toggle(this)">Item 3</a>
  </li>
  <div class="content hide">Content Goes here!</div>
  <li><a href="#" onclick="toggle(this)">Item 4</a>
  </li>
  <div class="content hide">Content Goes here!</div>
  <li><a href="#" onclick="toggle(this)">Item 5</a>
  </li>
  <div class="content hide">Content Goes here!</div>
</ul>

但最好使用jQuery-event-binding而不是Inline-event-binding

function toggle() {
  $(this).parent().next('.content').toggleClass('hide'); //this will refer to current element!
}
$('li a').on('click', toggle);
.hide {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<ul>
  <li><a href="#">Item 1</a>
  </li>
  <div class="content hide">Content Goes here!</div>
  <li><a href="#" onclick="toggle(this)">Item 2</a>
  </li>
  <div class="content hide">Content Goes here!</div>
  <li><a href="#">Item 3</a>
  </li>
  <div class="content hide">Content Goes here!</div>
  <li><a href="#">Item 4</a>
  </li>
  <div class="content hide">Content Goes here!</div>
  <li><a href="#">Item 5</a>
  </li>
  <div class="content hide">Content Goes here!</div>
</ul>

答案 1 :(得分:0)

HTML代码

<a (click)="showparent($event)" class="collapsible-header">show next element</a>
<div class="collapsible-body" style="display:none">
   <ul>
     <li>Node2</li>
     <li>Node2</li>
     <li>Node2</li>
   </ul>
</div>

TypeScript代码

showparent(elem){
    const target = elem
    const display = target.toElement.nextSibling.style.display

    if(display == 'block'){
      target.toElement.nextSibling.style.display = 'none'
    }else{
      target.toElement.nextSibling.style.display = 'block'
    }
  }