如何在 JavaScript 中使用括号表示法将函数附加到对象?
我正在编写一个 javascript,它应该将上下文菜单附加到文档中的元素。上下文菜单的 jquery 插件需要上下文菜单的 id 和选项对象。选项对象有一个名为“绑定”的属性,该属性应该具有键/值对,其中键是菜单项的 ID,值是单击时调用的函数。
问题是,我尝试填充的绑定对象在使用括号概念时不会将函数附加为值,而我需要它,因为无法提前确定菜单项的 id。
var bindings = {};
var bindingsFunction = function(t){
alert('Trigger was ' + t.id + '\nAction was Open');
};
var $listItems = $contextMenu.find('li');
$listItems.each(function(index, item){
var key = '' + item.id;
bindings[key] = bindingsFunction;
});
console.log('bindings is empty', bindings);
var result = $icon.contextMenu(contextMenuId, {
bindings: bindings
});
I'm writing a javascript that is supposed to attach a context menu to an element in the document. The jquery plugin for the context menu requires an id of the context menu and an options object. The options objects has a property called bindings that should have key/value pairs where the key is an id of a menu item and the value is a function invoked upon click.
The problem is that the bindings object that I'm trying to populate doesn't attach functions as values when using bracket notion, and I need it since, the menu items' id's cannot be determined in advance.
var bindings = {};
var bindingsFunction = function(t){
alert('Trigger was ' + t.id + '\nAction was Open');
};
var $listItems = $contextMenu.find('li');
$listItems.each(function(index, item){
var key = '' + item.id;
bindings[key] = bindingsFunction;
});
console.log('bindings is empty', bindings);
var result = $icon.contextMenu(contextMenuId, {
bindings: bindings
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这可能只是 Firebug 的“buggy”(?)显示。示例:
将显示:
看起来像一个空对象,但如果单击它,您将看到内容。
That might be just a "buggy"(?) display from Firebug. Example:
will display:
Looks like an empty object, but if you click on it you'll see the content.
它在 Chrome 中运行,所以我记得我正在开发 Firefox 4 Beta,所以我只是重新启动 Firefox,它就神奇地运行了。如果我可以再次重现它,我将能够提供更多细节。
It was working in Chrome, so I remembered that I'm working on a Firefox 4 Beta, so I just restarted Firefox and it magically worked. If I could reproduce it again I would be able to provide more details.
您没有包含脚本正在处理的 HTML,但我的猜测是正在选择的
li
元素没有id
属性。因此,当您将item.id
分配给key
时,它是一个空字符串,因此不是有效的属性名称。如果你在每个
li
上添加一个id
,它应该可以正常工作:http://jsfiddle.net/8TL7u/You didn't include the HTML that your script is working on, but my guess is that the
li
elements that are being selected do not have anid
property. As a result, when you assignitem.id
tokey
, it's an empty stringand thus not a valid property name.If you tack an
id
on eachli
, it should work just fine: http://jsfiddle.net/8TL7u/