[英]Javascript/Jquery Object Literal version, perform function on variable request
I have this code: 我有以下代码:
var ST = {
city: 'a#cityId:eq(2)',
state: 'div.location:eq(1)',
zip: 'p#zipcodes:eq(3)',
people: 'div.population :input',
autoload: function(selector) {
var elem = $(selector).get(0);
if (!elem || elem == 'undefined' || elem.length == '0') {
return false;
}
return elem;
},
};
Can I request the variable City for example, and have it automatically executed through autoload function? 例如,我可以请求变量City并通过自动加载功能自动执行该变量吗?
This is what I'm trying to achieve: 这是我要实现的目标:
ST.city ? ST.city.click() : '';
If you want to just do ST.city.click()
without worrying about whether anything matches the selector, stick with using a jQuery set rather than trying to use the DOM element directly. 如果您只想执行
ST.city.click()
而不必担心任何内容是否与选择器匹配,请坚持使用jQuery集而不是尝试直接使用DOM元素。
If you can rely on having Object.defineProperty
(support is currently reasonable , but it's not in IE8 for normal objects for instance), you can do this: 如果您可以依靠拥有
Object.defineProperty
(目前支持合理 ,但是在IE8中不支持普通对象),则可以执行以下操作:
var ST = {};
Object.defineProperties(ST, {
"city": {
get: function() {
return $('a#cityId:eq(2)'); // (But see Mottie's note about this selector)
}
},
"state": {
get: function() {
return $('div.location:eq(1)');
}
},
// ...and so on
});
Since the getters for the properties return jQuery sets, you can happily call click
on them even if they're empty: 由于属性的getter返回jQuery集,因此即使它们为空,您也可以高兴地
click
它们:
ST.city.click();
The above can be make briefer, I left it verbose for clarity. 以上可以使内容更简短,为清楚起见,我将其保留为冗长的内容。 Here's the short version:
这是简短的版本:
var ST = {
city: 'a#cityId:eq(2)',
state: 'div.location:eq(1)',
zip: 'p#zipcodes:eq(3)',
people: 'div.population :input'
};
$.each(ST, function(key, value) {
Object.defineProperty(ST, key, {
get: function() {
return $(value);
}
});
});
But if you need to support older browsers, you'll need a function call. 但是,如果您需要支持较旧的浏览器,则需要一个函数调用。 You could make
ST
itself the function: 您可以使
ST
本身具有以下功能:
var ST = function(selector) {
return $(ST.selectors[selector]);
};
ST.selectors = {
city: 'a#cityId:eq(2)',
state: 'div.location:eq(1)',
zip: 'p#zipcodes:eq(3)',
people: 'div.population :input'
};
Usage: 用法:
ST('city').click();
Or make a property on ST
the function: 或者在
ST
设置一个属性:
var ST = {
city: 'a#cityId:eq(2)',
state: 'div.location:eq(1)',
zip: 'p#zipcodes:eq(3)',
people: 'div.population :input',
autoload: function(selector) {
return $(this[selector]);
}
};
Usage: 用法:
ST.autoload('city').click();
ST.autoload(ST.city) ? $(ST.city).click() : "";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.