[英]How to show a div when a particular button is clicked,
这是我的js代码:
我想单击第一个按钮来调用一个新类,它起作用,但是,每个按钮都做同样的工作。 当我单击第二个按钮时,这也会调用一个新的类。请帮助我解决这个问题。
<script> $(document).ready(function(){ $("button").click(function(){ /*button click event*/ $(".new").toggle(); /*new class calling */ }); }); </script>
这是我的html代码:
<button>first</button><br> <button>second</button><br> <button>third</button><br> <div class="new" style = "display: none;">hi.</div> <!--i need to call only this class--> <div class="old"><a href="www.google.com">hello.</a></div>
您必须为该特定按钮设置一个ID,然后使用ID将点击事件处理程序附加到该特定按钮。 这是代码。
<button id ='myBtn' >first</button><br>
$("#myBtn").click(function(){ /*button click event*/
$(".new").toggle(); /*new class calling */
});
您可以使用contains('first')
。
问题是您使用button
作为选择器,将无法理解实际单击了哪个按钮。
我建议,为了使jQuery理解,您应该为该元素提供任何特定的ID。
但是,如果要基于DIV中的文本进行操作,则可以使用contains('first')
。
$(document).ready(function(){ $("button:contains('first')").click(function(){ /*button click event*/ $(".new").toggle(); /*new class calling */ }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button>first</button><br> <button>second</button><br> <button>third</button><br> <div class="new" style = "display: none;">hi.</div> <!--i need to call only this class--> <div class="old"><a href="www.google.com">hello.</a></div>
$(document).ready(function() { $("button").eq(0).click(function() { /*button click event*/ $(".new").toggle(); /*new class calling */ }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <button>first</button> <br> <button>second</button> <br> <button>third</button> <br> <div class="new" style="display: none;">hi.</div> <!--i need to call only this class--> <div class="old"><a href="www.google.com">hello.</a> </div>
使用.eq()
选择需要单击的按钮
注意:eq()是基于索引的,从0开始
如果您想单击第一个按钮来调用新课程,则可以通过多种方法进行。这里正在检查单击的文本以使第一个按钮单击
<script>
$(document).ready(function(){
$("button").click(function(){ /*button click event*/
if ($(this).text() == "first" ) $(".new").toggle(); /*new class calling */
});
});
</script>
设置id
更好
<button id="first">first</button><br>
<button>second</button><br>
<button>third</button><br>
<script>
$(document).ready(function(){
$("#first").click(function(){ /*specific button click event*/
$(".new").toggle(); /*new class calling */
});
});
</script>
使用$("Button")
您指的是Button元素,而不是某个按钮,因此每个按钮都将执行相同的操作。 您应该给按钮指定一个ID,然后根据其ID对其进行调用。
喜欢:
<button id="firstBtn">first</button><br>
<button id="secondBtn">second</button><br>
<button id="thirdbtn">third</button><br>
然后使用ID选择器#
调用它们,如下所示: $("#firstBtn").click()..
删除内联样式并使用单独的CSS类
$(document).ready(function() {
$("button").click(function() { /*button click event*/
$(".new").toggleClass('hide'); /*new class calling */
});
});
的CSS
.hide {
display:none;
}
给按钮赋予id,n相应地调用它们,例如
$("#first").click(function(){
$(".new").toggle();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.