简体   繁体   English

对多个Field和div使用动态jQuery函数

[英]use a dynamic jQuery function for more than one Field and div

I have a jQuery code that gets the value of the text input and add its value to a div class. 我有一个jQuery代码,它获取文本输入的值并将其值添加到div类。 while following code works fine, i am trying to find out how to make this function work more dynamic for more than one text input and more than one divs, without copying the same script for each input and div again and again. 虽然下面的代码可以正常工作,但我试图找出如何使此功能对于一个以上的文本输入和一个以上的div更动态地工作,而不是为每个输入和div一次又一次地复制相同的脚本。

 jQuery(document).ready(function($) { function checkForInput(element) { var value = $('.my-input-1').val(); $("#myDiv_1").removeClass().addClass(value); } $('input.my-input-1').on('change keyup', function() { checkForInput(this); }); }); jQuery(document).ready(function($) { function checkForInput(element) { var value = $('.my-input-2').val(); $("#myDiv_2").removeClass().addClass(value); } $('input.my-input-2').on('change keyup', function() { checkForInput(this); }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" class="my-input-1" value=""> <input type="text" class="my-input-2" value=""> <div id="myDiv_1" class=""> First Div </div> <div id="myDiv_2" class=""> Second Div </div> 

You can use an attribute for each input that its value represents the id of the div 您可以为每个input使用一个属性,该属性的值表示divid

 jQuery(document).ready(function($) { $('input.class-input').on('change keyup', function() { const $this = $(this); const value = $this.val(); const divId = $this.data('for'); $(`#${divId}`).removeClass().addClass(value); }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" class="class-input" value="" data-for="myDiv_1"> <input type="text" class="class-input" value="" data-for="myDiv_2"> <div id="myDiv_1" class=""> First Div </div> <div id="myDiv_2" class=""> Second Div </div> 

In case if you don't want to have identical classes for input elements.(As per your code.) Hope it helps. 如果您不想为输入元素使用相同的类。(根据您的代码。)希望对您有所帮助。

 jQuery(document).ready(function($){ function checkForInput(elementClass,elementValue) { var inputNumber= elementClass.substr(elementClass.length-1); var divclass='#myDiv_'+inputNumber; $(divclass).removeClass().addClass(elementValue); } $('input.my-input-1').on('change keyup', function() { checkForInput($(this).attr('class'),$(this).val()); }); $('input.my-input-2').on('change keyup', function() { checkForInput($(this).attr('class'),$(this).val()); }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" class="my-input-1" value=""> <input type="text" class="my-input-2" value=""> <div id="myDiv_1" class=""> First Div </div> <div id="myDiv_2" class=""> Second Div </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM