将jQuery代码应用于多个文本区域 [英] Apply jquery code to multiple textareas
本文介绍了将jQuery代码应用于多个文本区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些有效的代码,但是有很多重复: http://jsfiddle.net/6Wp2j/25/
I have some code which is working but I have a lot of duplication: http://jsfiddle.net/6Wp2j/25/
$('input.apple').on('keyup', function() {
$("div.apple").html(this.value);
});
$('input.orange').on('keyup', function() {
$("div.orange").html(this.value);
});
$('input.banana').on('keyup', function() {
$("div.banana").html(this.value);
});
我想知道是否有一种方法可以将项目放入某种数组中,以便可以将相同的代码应用于多个不同的字段.
I was wondering if there is a way to put the items into some sort of array, so that I can have the same code apply to several different fields.
推荐答案
您可以定位所有输入,也可以只给它们一个通用的目标类,然后提取一些东西,我使用了该类,但是如果元素具有多个类,等等:
You can target all inputs, or just give them a common class to target, and extract something, I used the class, but data attributes would be easier if the elements had multiple classes etc :
$('input').on('keyup', function() {
$('.'+this.className).html(this.value);
});
如上所述,如果元素具有多个类,请使用数据属性:
as noted above, if the elements have multiple classes, use data attributes :
<input class="input" data-id="apple" >
<input class="input" data-id="orange" >
<input class="input" data-id="banana" >
JS
$('.input').on('keyup', function() {
$('.' + $(this).data('id')).html(this.value);
});
这篇关于将jQuery代码应用于多个文本区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文