【发布时间】:2019-07-17 21:52:44
【问题描述】:
我有一个简单的是/否按钮选择的代码,它将自动填充要在表单中使用的输入值。我的问题是如何简化代码的 jquery 部分?因为我必须添加更多是/否问题。
$('#y01').click(function() {
$('#y01').css({'background':'#0080FF', 'color':'white'});
$('#n01').css({'background':'transparent', 'color':'#808080'});
$('#ans01').val('Yes');
});
$('#n01').click(function() {
$('#y01').css({'background':'transparent', 'color':'#808080'});
$('#n01').css({'background':'#0080FF', 'color':'white'});
$('#ans01').val('No');
});
$('#y02').click(function() {
$('#y02').css({'background':'#0080FF', 'color':'white'});
$('#n02').css({'background':'transparent', 'color':'#808080'});
$('#ans02').val('Yes');
});
$('#n02').click(function() {
$('#y02').css({'background':'transparent', 'color':'#808080'});
$('#n02').css({'background':'#0080FF', 'color':'white'});
$('#ans02').val('No');
});
body,
html {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
background-color: fff;
}
.button {
background: transparent;
color: white;
padding: 15px 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
border-radius: 12px;
width: 100px;
}
.button1 {
color: #808080;
border: 2px solid #e7e7e7;
}
.button:active,
.button:focus,
.button:visited {
outline: none;
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td,
th {
border: none;
padding: 15px;
width: 50%;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td style="text-align:right;">
Do you have any question #1?
</td>
<td>
<input type="text" id="ans01" hidden/>
<input type="button" id="y01" class="button button1" value="Yes" />
<input type="button" id="n01" class="button button1" value="No" />
</td>
</tr>
<tr>
<td style="text-align:right;">
Do you have any question #2?
</td>
<td>
<input type="text" id="ans02" hidden/>
<input type="button" id="y02" class="button button1" value="Yes" />
<input type="button" id="n02" class="button button1" value="No" />
</td>
</tr>
</table>
【问题讨论】:
标签: javascript jquery html dry togglebutton