jQuery using index()
jQuery using index()
我很难解释我想要什么,但我会试一试。
好的,左边是html。
<div></div>
<div></div>
<div></div>
<div></div>
以下是右侧输出的内容。
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
我试着让它变得这样,当你点击左边的第一个div时,右边的第一个divs就会出现,当你单击左边的第二个divs时,右边第二个div就会出现,而右边的所有其他div都会再次隐藏,以此类推。我知道你可以用jQuery中的.index()来做,但我想知道我是否能得到一些关于如何做的帮助。谢谢!
类似的东西?
标记
<div class="left">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
<div class="right">
<div class="block">Result 1</div>
<div class="block">Result 2</div>
<div class="block">Result 3</div>
<div class="block">Result 4</div>
</div>
JS
$(function(){
$('.left > div').on('click', function(){
//Just show the respective block div based on the clicked index and hide its siblings that are visible.
$('.block').eq($(this).index()).show().siblings('.block:visible').hide();
});
});
演示
有一点滑动效果
$(function () {
$('.block').eq(0).show();
$('.left > div').on('click', function () {
var elemToShow = $('.block').eq($(this).index()); //Get the element to show
$('.block:visible').stop().slideUp(1000, function () { // slide up the visible block div
elemToShow.stop().slideDown(1000); // once the animation finishes shidedown the element to show
});
});
});
演示幻灯片效果
演示渐变效果
假设您将把一个left
类放在左边的div
s:上
var $blocks = $('.block'),
$left = $('.left');
$('.left').click(function () {
$blocks.hide().eq( $left.index(this) ).show();
});
小提琴在这儿:http://jsfiddle.net/YddrP/
首先,您必须检测左侧元素上的点击。在回调函数中,您必须找到单击的div的索引,然后找到右侧索引与数字匹配的show()
。
假设左侧的div在一个类为left
的容器中,右侧的div在right
:中
$('.left').on('click', 'div', function(){ //bind the click event to the left divs
$('.right div') // select all the divs inside .right
.hide() // hide all the divs
.eq( $(this).index() ) // select the one that matches the clicked index
.show(); // show it
});
这是一个演示。
这是on()
的文档。
这是eq()
的文档。
是的,您可以尝试.index()和:eq().index()返回元素的数字索引,而:eq()通过数字索引返回元素。
假设左div位于类为'left'的外部div内,右div位于'right'内
$('.left div').click(function () {
$('.right div').hide();
var i = $('.left div').index(this);
$('.right div:eq(' + i + ')').show()
});
相关文章:
- Emberjs应用程序加载在除Index之外的所有路由上
- 分析高度属性时出现意外值{{specs.height}}.index.html
- 主干模板:index.jst.eco到index.jst.ejs
- 如何通过引用var Using DataTables来进行分页或排序
- 将 jQuery 代码添加到 Index.aspx 页面
- AngularJS-需要在index.html页面中访问来自服务的数据
- 更改基于它的Select OPTION's INDEX(Jquery)
- 尝试创建一个具有z-index的堆叠菜单'使用HTML5/CSS3/JS
- Object.prototype using 'this'
- index.html使用webpack开发服务器未重新加载
- using LocalStorage ionic 2
- 从index.html调用函数,该函数无限循环
- jQuery Replacing, Using arrays
- Using jQuery with classes from ES6
- RouteChangeStart事件在初始index.html页面加载时触发
- Dropdownlist using javascript
- Is (!~index) faster than (index === -1)?
- KOValidation在错误消息中获取可观察值、$index()、$data等
- 为什么我可以'不要使用xx[this.index].style.display?它's说“;无法读取属性
- jQuery using index()