我如何在 jQuery 的点击功能中使用动态 div id
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16174975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how i can use dynamic div id in click function of jQuery
提问by PSR
<div id="div1" style="display:none;" class="abcd">
<p>Black</p>
</div>
<div id="div2" style="display:none;" class="abcd">
<p>Red</p>
</div>
<div id="div3" style="display:none;" class="abcd">
<p>Blue</p>
</div>
<input type="button" value="Black" id="black" class="btn"
onClick="showDiv('div1')"/>
<input type="button" value="Red" id="red" class="btn"
onClick="showDiv('div2')"/>
<input type="button" value="Blue" id="blue" class="btn"
onClick="showDiv('div3')"/>
function showDiv(divId){
$('.abcd').hide();
$('#'+divId).show();
}
I am using the above code in javascript to show hide divs when corresponding button is clicked and remaining divs need to hide.I am passing the div id from javascript function.
我在 javascript 中使用上面的代码在单击相应的按钮时显示隐藏 div 并且需要隐藏剩余的 div。我正在从 javascript 函数传递 div id。
$('#btn').click(function(){
});
Here how i can pass those divid dynamically in jQuery .click event.Thanks in advance....
在这里,我如何在 jQuery .click 事件中动态传递那些除法。提前致谢....
回答by Andy
This would be a bit of a cleaner method, without onclick:
这将是一个更干净的方法,没有 onclick:
<input data-id="div1" type="button" value="Black" id="black" class="btn" />
<input data-id="div2" type="button" value="Red" id="red" class="btn" />
<input data-id="div3" type="button" value="Blue" id="blue" class="btn"/>
$('.btn').click(function(){
$('#'+$(this).data('id')).toggle();
});
this way you could show/toggle any element if you insert its id into the data-id
attribute of the button.
这样,如果您将其 id 插入data-id
按钮的属性中,您就可以显示/切换任何元素。
回答by Eli
Since you give your input class btn
, you need to use .
instead of #
for reference. Then you can do like this to show the div according to the button clicked:
由于您提供输入类btn
,因此您需要使用.
而不是#
作为参考。然后你可以像这样根据点击的按钮显示div:
$('.btn').click(function(i) {
var index = $(this).index('input') + 1;
$('#div' + index).show().siblings('div').hide();
});
回答by DarkAjax
You can do it like this:
你可以这样做:
$('.btn').click(function(){
$('.abcd').not(':contains('+$(this).val()+')').hide();
$('.abcd:contains('+$(this).val()+')').show();
});
This way you won't need the onClick
attribute on your <button>
elements as you'll look based on the fact that your <div>
elements have a <p>
with a text equal to the value of the clicked button...
这样,您将不需要元素onClick
上的属性,<button>
因为您将根据<div>
元素具有<p>
的文本等于单击按钮的值来查看...