[英]jQuery show/hide div if button group pressed
The first function shows the .check
div if any of the inputs that have data-target="check"
are checked. 如果.check
所有具有data-target="check"
的输入,则第一个函数显示.check
div。
Now I am trying to simulate the same checked / unchecked
states of the checkboxes and have the function work the same way but for buttons
that are clicked
and then un-clicked
by pressing the #clear
button. 现在,我试图模仿相同checked / unchecked
的复选框的状态,并有功能的工作方式相同,但对于buttons
是clicked
,然后un-clicked
按#clear
按钮。
$('input').on('change', function() { var source = $(this); var target = $('.' + source.attr('data-target')); if ($('input[data-target=' + source.attr('data-target') + ']:checked').length) target.show(); else target.hide(); }); $('button').on('click', function() { var clear = $("#clear"); if ($(this) !== clear) { var source = $(this); var target = $('.' + source.attr('data-target')); if ($('button[data-target=' + source.attr('data-target') + ']').length) target.show(); } else { if ($(this) === clear) { target.hide(); } } });
div { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="checkbox" name="name" data-target="check" value="1"> <input type="checkbox" name="name" data-target="check" value="2"> <input type="checkbox" name="name" data-target="check" value="3"> <button data-target="button" value="4"></button> <button data-target="button" value="5"></button> <button id="clear">clear</button> <div class="check">check</div> <div class="button">button</div>
You are doing a couple of things that are keeping this from working. 您正在做一些事情,使它无法正常工作。 One is how you're comparing objects - now how I used !$(this).is(clear)
, and the other is that you keep redefining target inside the $('button').on
... function. 一种是您如何比较对象-现在如何使用!$(this).is(clear)
,另一种是您始终在$('button').on
...函数中重新定义目标。 Here is how it should look, I changed the variable name for clarity: 这是它的外观,为清楚起见,我更改了变量名称:
var button_target;
$('input').on('change', function() {
var source = $(this);
var target = $('.' + source.attr('data-target'));
if ($('input[data-target=' + source.attr('data-target') + ']:checked').length) target.show();
else target.hide();
});
$('button').on('click', function() {
var clear = $("#clear");
if (!$(this).is(clear)) {
var source = $(this);
button_target = $('.' + source.attr('data-target'));
if ($('button[data-target=' + source.attr('data-target') + ']').length) button_target.show();
} else {
if ($(this).is(clear)) {
button_target.hide();
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.