重构jQuery函数
这里我有4个div标签。它工作得非常好,但我想知道是否有任何方法可以重构或连接对应于每个div的选择器重构jQuery函数,jquery,html,Jquery,Html,这里我有4个div标签。它工作得非常好,但我想知道是否有任何方法可以重构或连接对应于每个div的选择器 $('.expand-one').click(function () { $('.content-one').toggle(); }); $('.expand-two').click(function () { $('.content-two').toggle(); }); $('.expand-three').click(function () { $('.content-three')
$('.expand-one').click(function () {
$('.content-one').toggle();
});
$('.expand-two').click(function () {
$('.content-two').toggle();
});
$('.expand-three').click(function () {
$('.content-three').toggle();
});
$('.expand-four').click(function () {
$('.content-four').toggle();
});
<div class="expand-one>click to expand</div>
<div class="content-one">
<p>here is content</p>
</div>
<div class="expand-two>click to expand</div>
<div class="content-two">
<p>here is content</p>
</div>
<div class="expand-three>click to expand</div>
<div class="content-three">
<p>here is content</p>
</div>
<div class="expand-four>click to expand</div>
<div class="content-four">
<p>here is content</p>
</div>
$('.expand one')。单击(函数(){
$('.content one').toggle();
});
$('.展开两个')。单击(函数(){
$('.content two').toggle();
});
$('.expand three')。单击(函数(){
$('.content three').toggle();
});
$('.expand four')。单击(函数(){
$('.content-four').toggle();
});
单击展开
这里是内容
单击展开
这里是内容
这个怎么样
$('.展开一、.展开二、.展开三、.展开四')。单击(函数(e){
var contentIndex=e.target.className.substr(7,e.target.className.length);//请注意,7是一个固定的数字,在每种情况下都是“.expand-”
$('.content-'+contentIndex.toggle();
});
我同意使用公共类的建议。比如说:
HTML
。。。
...
JavaScript
$('.expand header')。单击(函数(){
$(this).next('.expand content').toggle();
}
但是,如果由于某种原因无法使用公共类,则可能会使用“class starts with”选择器语法,因此:
//为类名为“expand-”的每个元素单击句柄
$('[class^=“expand-”])。单击(函数(){
//切换以“content-”开头的类的“next”元素
$(this.next(“[class^=“content-”]).toggle();
}
不是按类选择,而是按数据属性选择,作为变量传递:
$('.expand')。单击(函数(){
$('.content[data attr='+$(this.data('attr')+']')。toggle();
});
.content{
显示:无
}
分区:第n个类型(1),
分区:第n个类型(2){
颜色:红色
}
分区:第n个类型(3),
分区:第n个类型(4){
颜色:绿色
}
分区:第n个类型(5),
分区:第n个类型(6){
颜色:蓝色
}
分区:第n个类型(7),
分区:第n个类型(8){
颜色:橙色
}
单击展开
这里是内容
单击展开
这里是内容
单击展开
这里是内容
单击展开
这里是内容
为每个“expand-”和“content-”div添加一个公共类并使用它们。确保这次关闭引号。因为content div元素总是紧跟其后,所以您可以使用$(this)。next()
。并为expand div元素提供一个公共类,这样您只需绑定一次click事件侦听器。如果您修复了类属性的错误,则很可能会有更多关于主题的内容