4 回答
TA贡献2012条经验 获得超12个赞
喜欢这个?
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-outline-primary" id="test-button" data-toggle="button" aria pressed="false" autocomplete="off">
Click Me
</button>
<input type="text" name="test-input" id="test-input" value="">
<script type="text/javascript">
$('#test-button').click(function()
{
const $testInput = $('#test-input');
if (!$('#test-input').val().length) {
$('#test-input').val("Value Populated");
} else {
$('#test-input').val("");
}
}
)
</script>
TA贡献1799条经验 获得超9个赞
您可以检查该值是否存在,如果该值存在,则将其删除。像这样试试吧
$('#test-button').click(function()
{
if($('#test-input').val() != "Value Populated"){
$('#test-input').val("Value Populated");
}else{
$('#test-input').val("");
}
}
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-outline-primary" id="test-button" data-toggle="button" aria pressed="false" autocomplete="off">
Click Me
</button>
<input type="text" name="test-input" id="test-input" value="">
另一个选项是在设置值时为输入设置数据属性。这将帮助您重置,即使输入已更改
$('#test-button').click(function()
{
let valueSet = $('#test-input').attr('data-set');
if(valueSet ==1){
$('#test-input').attr('data-set','0').val("");
}else{
$('#test-input').attr('data-set','1').val("Value Populated");
}
}
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-outline-primary" id="test-button" data-toggle="button" aria pressed="false" autocomplete="off">
Click Me
</button>
<input type="text" name="test-input" id="test-input" value="">
TA贡献1852条经验 获得超1个赞
您可以检查输入中是否有值“测试输入”,如果没有添加文本,否则删除文本 -
<script type="text/javascript">
$('#test-button').click(function()
{
if ($('#test-input').val == '' || $('#test-input').val == null) {
$('#test-input').val("Value Populated");
} else {
$('#test-input').val("");
}
}
)
</script>enter code here
TA贡献1815条经验 获得超13个赞
只需检查您是否有价值:
$(document).ready(function() {
$('#test-button').on('click',function() {
if ($('#test-input').val()) {
$('#test-input').val("")
} else {
$('#test-input').val("Value Populated")
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-outline-primary" id="test-button" data-toggle="button" aria pressed="false" autocomplete="off">
Click Me
</button>
<input type="text" name="test-input" id="test-input" value="">
添加回答
举报