gpt4 book ai didi

具有 2 个或更多对象的页面上的 javascript 设计模式

转载 作者:行者123 更新时间:2023-11-28 06:06:11 26 4
gpt4 key购买 nike

我需要选择正确的设计模式。我的页面有 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com