让我的jquery变短?
我想缩短我的JQuery。我知道使用这个元素和子元素是可能的,但我不知道它是如何工作的 我有一个元素是显示和隐藏的点击基本上。它们都有相同的ID,只是不同的类 如何才能做到这一点 这就是我的html的外观:让我的jquery变短?,jquery,toggle,this,parent-child,Jquery,Toggle,This,Parent Child,我想缩短我的JQuery。我知道使用这个元素和子元素是可能的,但我不知道它是如何工作的 我有一个元素是显示和隐藏的点击基本上。它们都有相同的ID,只是不同的类 如何才能做到这一点 这就是我的html的外观: <div id="spotparent"> <div id="spot" class="one" style="position: absolute; z-index: 103; width: 25px; height:25px;"> &
<div id="spotparent">
<div id="spot" class="one" style="position: absolute; z-index: 103; width: 25px; height:25px;">
<div id="ball"></div>
<div id="pulse"></div>
<div id="contentspot" class="one">
<img src="img/line-boost.png">
</div>
</div>
<div id="spot" class="two" style="position: absolute; z-index: 103; width: 25px; height: 25px;">
<div id="ball"></div>
<div id="pulse"></div>
<div id="contentspot" class="two">
<img src="img/line-tpu.png">
</div>
</div>
<div id="spot" class="three" style="position: absolute; z-index: 103; width: 25px; height:25px;">
<div id="ball"></div>
<div id="pulse"></div>
<div id="contentspot" class="three">
<img src="img/line-wrap.png">
</div>
</div>
<div id="spot" class="four" style="position: absolute; z-index: 103; width: 25px; height:25px;">
<div id="ball"></div>
<div id="pulse"></div>
<div id="contentspot" class="four">
<img src="img/line-support.png">
</div>
</div>
<div id="spot" class="five" style="position: absolute; z-index: 103; width: 25px; height:25px;">
<div id="ball"></div>
<div id="pulse"></div>
<div id="contentspot" class="five">
<img src="img/line.png">
</div>
</div>
<div id="spot" class="six" style="position: absolute; z-index: 103; width: 25px; height:25px;">
<div id="ball"></div>
<div id="pulse"></div>
<div id="contentspot" class="six">
<img src="img/line-knit.png">
</div>
</div>
<div id="spot" class="seven" style="position: absolute; z-index: 103; width: 25px; height:25px;">
<div id="ball"></div>
<div id="pulse"></div>
<div id="contentspot" class="seven">
<img src="img/line-signature.png">
</div>
</div>
</div>
所以它一直在重复
我相信这是可能的,使所有这些代码在两行,如果有人可以解释我的过程,我理解,这将是美妙的
谢谢您的时间。首先,您应该听取@empiric的建议,并且每页最多只能使用
id
一次<代码>id应该是唯一的属性,不能重复使用。我建议这样做,对类似的元素使用class
属性
<div id="spots">
<div class="spot" style="position: absolute; z-index: 103; width: 25px; height:25px;">
<div class="ball"></div>
<div class="pulse"></div>
<div class="content">
<img src="img/line-boost.png">
</div>
</div>
<!-- more spots... -->
</div>
第一:不要在一个文档中多次使用
ID
。这可能会导致错误,并且是无效的HTMLSecond,因为您的代码正在工作,不是吗?您的问题可能会更适合您
<div id="spots">
<div class="spot" style="position: absolute; z-index: 103; width: 25px; height:25px;">
<div class="ball"></div>
<div class="pulse"></div>
<div class="content">
<img src="img/line-boost.png">
</div>
</div>
<!-- more spots... -->
</div>
<script>
$('#spots .spot').on('click', function() {
$(this) //this refers to the clicked element, our .spot
.find('.content') //select child elements with class 'content'
.toggleClass('showcontent');
});
</script>