本文介绍了是否可以美化此JavaScript代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经完成了我的研究,但我找不到与我的问题有关的任何有用的东西。
I have done my research but i cant find anything useful that are related to my question.
原始JavaScript代码
$("#furniture1").keyup(function(){
samefunction();
});
$("#furniture2").keyup(function(){
samefunction();
});
$("#furniture3").keyup(function(){
samefunction();
});
$("#color1").keyup(function(){
samefunction();
});
$("#color2").keyup(function(){
samefunction();
});
$("#color3").keyup(function(){
samefunction();
});
我只能提出这个解决方案,还有更好的解决方案吗?
I can only come up with this solution, is there better solution?
var index_no = 0;
for(var i=1; i<=3; i++)
{
index_no++;
var name = '#furniture';
name += index_no;
$(name).keyup(function () {
samefunction();
});
var name = '#color';
name += index_no;
$(name).keyup(function () {
samefunction();
});
}
推荐答案
只需将选择器与<$分开c $ c>,。
$("#furniture1, #furniture2, #furniture3, #color1, #color2, #color3").keyup(function(){
samefunction();
});
示例
$("#furniture1, #furniture2, #furniture3, #color1, #color2, #color3").keyup(function(){
console.log(`Fired from the input ${this.id}`);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="furniture1">
<input id="furniture2">
<input id="furniture3">
对于动态,你需要一个循环。您可以减少循环中编写的代码,如
For dynamic you need a loop. You can just decrease the code written in the loop like
for(var i = 1; i <= 3; i++)
{
$(`#furniture${i}, #color${i}`).keyup(function () {
samefunction();
});
}
或者@Satpal在评论中提到你可以添加一个公共类所有元素并使用该类绑定事件处理程序,如。
Or as @Satpal have mentioned in the comments you can add a common class for all elements and use that class to bind the event handler like.
$(".someClass").keyup(function(){
console.log(`Fired from the input ${this.id}`);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="furniture1" class='someClass'>
<input id="furniture2" class='someClass'>
<input id="furniture3" class='someClass'>
这篇关于是否可以美化此JavaScript代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!