P粉0630399902023-08-14 14:21:09
让我们简化事情,创建一个单独的函数,并基于该函数在文本字段上应用您的逻辑。
示例:
$('#dropdown').change(function() { var selectedOption = $(this).val(); check(selectedOption); }); $('#inputField').on('input', function() { var selectedOption = $('#dropdown :selected').val(); check(selectedOption); }); function check(inp) { var value = $('#inputField').val(); if (inp === 'fixed') { $('#inputField').attr('maxlength', '20'); var formattedValue = '₹' + value.replace(/\D/g, '').replace(/(\d)(?=(\d{3})+(?!\d))/g, ','); $('#inputField').val(formattedValue); } else { $('#inputField').attr('maxlength', '2'); var formattedValue = value.replace(/\D/g, '') + '%'; $('#inputField').val(formattedValue); } }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="dropdown"> <option value="fixed">固定值</option> <option value="percentage">百分比</option> </select> <input type="text" id="inputField">