这肯定已经被问过/回答过,我只是不知道如何表达它,所以找不到任何东西
我有两个字段 street_1
和 street_2
,这两个字段的操作应该完全相同,所以我想知道是否可以以某种方式对这两个字段使用相同的函数字段,根据使用的字段,它会在 1
和 2
之间交替。
例如:
$('street_1').on('input', function(e){
document.getElementById('count1').innerHTML = $('street_1').value.length+'/'+ max;
if ($('street_1').value.length>max) {
document.getElementById('count1').style.color = "red";
}
else document.getElementById('count1').style.color = "black";
});
如果 street_2
是接收输入的字段,则所有 1
都应更改为 2
。
HTML
<div class="fieldset">
<h2 class="legend"><?php echo $this->__('Address') ?></h2>
<ul class="form-list">
<?php $_streetValidationClass = $this->helper('customer/address')->getAttributeValidationClass('street'); ?>
<li class="wide">
<label for="street_1" class="required"><em>*</em><?php echo $this->__('Street Address') ?></label>
<div style="position: relative;" class="input-box">
<input style="color: transparent; caret-color: black; z-index: 1;" type="text" name="street[]" value="<?php echo $this->escapeHtml($this->getAddress()->getStreet(1)) ?>" title="<?php echo $this->__('Street Address') ?>" id="street_1" class="street
input-text
form-control
required-entry
<?php echo $_streetValidationClass ?>" />
<span id="street1span" class="input-text" style="display: inline-block; white-space: nowrap; overflow-x: hidden; width: 98%; position: absolute; top: 0.25px; left: 2px; padding: 1px; z-index: 2; pointer-events: none;" ></span>
<span id="count1" class="input-text" style="position: absolute; display: block; right: 5px; top: 2px; z-index: 9;"></span>
</div>
我再次进行了完全相同的设置,只是使用了 2
,因此 street_1
、street2span
和 count2
最佳答案
street_1
和 street_2
是所需输入的 ids
,因此您必须按顺序使用 $
符号做一个jquery
选择器。
此外,我建议您不要将 javascript 与 jquery 混合使用。仅使用一个。
我用了closest , find和 eq为了找到属于所需输入
的span
元素。
您可以通过以下方式进行:
$('#street_1,#street_2').on('input', function(e){
let count=$(this).closest('div').find('span').eq(1);
count.text($(this).value.length+'/'+ max);
if ($(this).value.length>max) {
count.css('color','red');
}
else count.css('color','black');
});
关于javascript - 根据所使用的字段而变化的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45810462/