Streamlining my javascript with a function
i have a series of select lists, that i am using to populate text boxes with ids. so you click a select option and another text box is filled with its id.
with just one select/id pair this works fine, but i have multiples, and the only thing that changes is the id of the select and input.. in fact just the ending changes, the inputs all start with featredproductid and the select ids all start with recipesproduct and then both end with the category.
i know that listing this over and over for each category is not the way to do it. i think i need to make an array of the categories var cats = ['olive oil', "grains", "pasta"] and then use a forEach function? maybe?
here is the clunky code
window.addEvent('domready', function() {
$('recipesproductoliveoil').addEvent('change', function(e){
pidselected = this.options[this.selectedIndex].getProperty('value') ;
$("featuredproductidoliveoil").setProperties({
value: pidselected}); ;
});
$('recipesproductgrains').addEvent('change', function(e){
pidselected = this.options[this.selectedIndex].getProperty('value') ;
$("featuredproductidgrains").setProperties({
value: pidselected}); ;
});
$('recipesproductpasta').addEvent('change', function(e){
pidselected = this.options[this.selectedIndex].getProperty('value') ;
$("featuredproductidpasta").setProperties({
value: pidselected}); ;
});
$('recipesproductpantry').addEvent('change', function(e){
pidselected = this.options[this.selectedIndex].getProperty('value') ;
$("featuredproductidpantry").setProperties({
value: pidselected}); ;
});
});
keep in mind this is mootools 1.1 (no i cant update it sorry). i am sure this is kind of basic, something i seem to have wrapping my brain around. but i am quite sure doing it as above is not really good...
You're close. This is how you could do it:
var cats = ['oliveoil', 'grains', 'pasta'];
for (i in cats) {
addChangeFunction(cats[i]);
}
function addChangeFunction(name) {
$('recipesproduct' + name).addEvent('change', function(e) {
pidselected = this.options[this.selectedIndex].getProperty('value');
$('featuredproductid' + name).setProperties({
value: pidselected
});
});
}
像这样的东西可能会有所帮助:
function bindSelectFeature(select, featured) {
$(select).addEvent('change', function(e){
pidselected = this.options[this.selectedIndex].getProperty('value') ;
$(featured).setProperties({
value: pidselected
});
});
});
bindSelectFeature('recipesproductpasta','featuredproductidpasta');
链接地址: http://www.djcxy.com/p/1466.html
上一篇: JavaScript点击处理程序在for循环中没有像预期的那样工作
下一篇: 简化我的JavaScript与功能