我的目标是隐藏所有div(通过css类),然后在模态样式弹出窗口中显示它们(再次通过css完成)。例如:
<a href="" id="speclinkOpen">Show Spec</a>
<div class="speclink">
<h1>This is spec 1</h1>
<a id="speclinkClose">Close</a>
</div>
<a href="" id="speclinkOpen">Show Spec</a>
<div class="speclink">
<h1>This is spec 2</h1>
<a id="speclinkClose">Close</a>
</div>
divs(speclink 类)中的内容是隐藏的。 当他们按下按钮(ID speclinkOpen)时,我希望它显示相关内容,因此如果单击顶部按钮,则为"这是规范1",如果单击底部按钮,则为"这是规范2"。
我知道我需要使用 on.click THIS 而不是实际的类名,但不完全确定我该怎么做。.谁能为我提供一些启示?
从本质上讲,jQuery 将以覆盖样式显示div 内容,但它如何知道根据使用相同的类名按下哪个按钮作为 im 加载哪个div 内容?以不同的方式命名不是一种选择,因为我有很多,但也许我完全以错误的方式解决问题?谢谢约翰。
看看数据属性。
你可以在你的html中做一些事情:
<a href="#" class="speclinkOpen" data-div="div1">Show Spec</a>
<div class="speclink" id="div1">
<h1>This is spec 1</h1>
<a id="speclinkClose1">Close</a>
</div>
<a href="#" class="speclinkOpen" data-div="div2">Show Spec</a>
<div class="speclink" id="div2">
<h1>This is spec 2</h1>
<a id="speclinkClose2">Close</a>
</div>
在jQuery脚本中:
$(function(){
$('img.speclinkOpen').on('click', function(){
var id = $(this).data('div'); // take the id to "highlight"
$('#' + id).addClass('modal'); // do whatever you want in with class or .css()
});
});
编辑
如果由于无法将 id 属性唯一分配给div 而无法使用数据属性:
$(function(){
$('img.speclinkOpen').on('click', function(){
$(this).next('div.speclink').addClass('modal'); // do whatever you want in with class or .css()
});
});