作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要选择正确的设计模式。我的页面有 2 个从同一构造函数创建的对象。我遇到的问题是检测哪个对象正在获取单击事件。
我在创建对象后执行此操作:
$("table tr, table button,.dataTables_paginate a").click(function (e) {
**myTableName.buttonPressed($(this));**
});
和
buttonPressed: function (el) {
if (el.is('a') && el.closest('li').hasClass('paginate_button')) {
var objName = el.attr('aria-controls');
debugger;
}
else {
var objName = $(el).closest('table').attr('id');
}
**this.getName(objName);**
tbl = myTableName.tbl;
editor = myTableName.editor;
//myTableName.acl(myTableName.currentForm);
},
然后
getName: function (objName) {
// search through the global object for a name that resolves to this object
for (var name in window)
if (window[name] == this) {
if (objName) {
myTableName = window[objName];
//window.myState[this.myInstanceName] = jQuery.extend({}, this);
break;
} else {
window[name] = this;
window[window[name]] = window[name];
myTableName = window[window[name]];
// window.myState[this.myInstanceName] = jQuery.extend({}, this);
}
break;
}
},
除了这些都是全局变量之外,我不认为这是正确的方法。
想法?
最佳答案
看来您应该使用自定义属性。自定义属性允许您将其他相关数据存储到任何 DOM 元素。一种使用方法是将 DOM 与某些 JS 字节码相关联。当您必须向后工作(即查找 HTML 元素的相关对象)时,这尤其有用。标准规定这些属性必须以 data-
开头(尽管从技术上讲,您可以使用浏览器未使用的任何内容,但不建议这样做)。这是一个例子:
HTML:
<table data-instance-name="name1">
...
<button>Action</button>
<a>Another action</a>
</table>
<table data-instance-name="name2">
...
<button>Action</button>
<a>Another action</a>
</table>
JS:
$( 'table button, table a' ).on('click', function() {
var name = $(this).closest('table').attr('data-instance-name'),
table = tables[name];
});
关于具有 2 个或更多对象的页面上的 javascript 设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36837917/
我是一名优秀的程序员,十分优秀!