JavaScript/jQuery 简写函数定义
我正在使用一个 jQuery 插件,其功能定义如下:
$('#mydiv').pluginAction({
someproperty: val,
format: 'mm hh',
labels: ['yes', 'no', 'maybe'],
labels1: ['never', 'always']
});
在我的 HTML 页面中,我有多个 DIV,它们具有相同的 format
、labels
、属性>labels1
,但 someproperty
的值不同。是否有某种类型的 JavaScript 表示法可以用来缩短定义,这样我就不必有重复的代码?
I'm using a jQuery plugin that has its functions defined as such:
$('#mydiv').pluginAction({
someproperty: val,
format: 'mm hh',
labels: ['yes', 'no', 'maybe'],
labels1: ['never', 'always']
});
In my HTML page, I have multiple DIVs that have the same properties for format
, labels
, labels1
, but different values for someproperty
. Is there some type of JavaScript notation I can take advantage of to shorten the definition so that I don't have to have duplicate code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有几种方法可以解决这个问题:
创建一个填补空白的函数;或
如果该插件是您的,请将这些值默认为您想要的值。
(1)的例子:
There are a couple of ways of dealing with this:
Create a function which fills in the blanks; or
If the plugin is yours, default those values to what you want.
Example of (1):
Cletus 有一个非常好的答案,它允许您生成非常可读的代码。这可能是您的情况的最佳解决方案。
仅作为记录,类似以下内容也是可能的。您可以创建一个存储所有固定属性的对象文字,然后在需要时使用
jQuery#extend
。Cletus has a very good answer, which allows you to produce very readable code. This is probably the best solution in your case.
Just for the record, something like the following would also be possible. You could create an object literal storing all fixed properties, and then just specify add extra properties (such as
someProperty
in your example) when needed by usingjQuery#extend
.复制此类代码并没有什么问题。它实际上清楚地表明了哪种行为适用于给定的 div。但是,如果您正在谈论数百个重复项,请使用其他人的建议。
There's nothing wrong with duplicating that sort of code. It actually makes it clear what sort of behavior applies on that given div. If however you're talking of hundreds of duplications, use what other people have suggested.