我想在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');
}
谢谢你们
答案 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'
}
}