我有这样写的 jQuery 扩展:
$.fn.GetBootstrapDeviceSize = function() {
var cMobileSize = $('#users-device-size').find('div:visible').first().attr('id');
return (cMobileSize === "xs" || cMobileSize === "sm");
为了调用它,我使用:
$().GetBootstrapDeviceSize()
有没有办法像这样调用同一个函数:
$.GetBootstrapDeviceSize()
或者甚至像这样:
$.GetBootstrapDeviceSize
最佳答案
Is there a way to call this same function like this:
$.GetBootstrapDeviceSize()
是的,把它放在 $
上,而不是放在 $.fn
上:
$.GetBootstrapDeviceSize = function() {
// ^^
var cMobileSize = $('#users-device-size').find('div:visible').first().attr('id');
return (cMobileSize === "xs" || cMobileSize === "sm");
}
Or perhaps even like this:
$.GetBootstrapDeviceSize
是的,但这可能不是最佳实践。您可以通过为 $
上的该属性创建一个 getter 来实现:
Object.defineProperty($, "GetBootstrapDeviceSize", {
get: function() {
var cMobileSize = $('#users-device-size').find('div:visible').first().attr('id');
return (cMobileSize === "xs" || cMobileSize === "sm");
}
});
然后访问 $.GetBootstrapDeviceSize
将运行该函数并为您提供返回值。不过,我可能只是将其称为 BootstrapDeviceSize
,因为您访问它时就好像它不是一种方法一样,所以使用名词而不是动词才有意义。
关于javascript - 调用不带括号的 jquery 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51673452/