Legend
September 5, 2025
Answered
How to convert a function into a method that can be directly applied to each object.
- September 5, 2025
- 2 replies
- 397 views
For example:
I have a function that adjusts the width of selected table to the width of the textFrame.
Now I have selected a textFrame.
I used a loop.
I want each table to apply this once:
tbs[i].tabFitToTextFrame()If you remove tbs[i] and use:
tabFitToTextFrame();only the first tab will be modified.
I try Like this:
It doesn't seem to be working.
//var sel = app.documents[0].selection;
var doc = app.activeDocument;
var tbs = doc.selection[0].tables;
//var tbs = getTable(doc.selection);
alert(tbs);
//alert(sel.tables);
if (tbs.length > 0) {
for (var i = 0; i < tbs.length; i++) {
alert(tbs[i]);
tabFitToTextFrame();
}
}
function tabFitToTextFrame() {
var doc = app.activeDocument,
item = doc.selection[0];
var myTable = getTable(doc.selection);
parentWidth = myTable.parent.geometricBounds[3] - myTable.parent.geometricBounds[1];
factor = parentWidth / myTable.width;
for (col = 0; col < myTable.columns.length; col++)
myTable.columns[col].width *= factor;
}
function getTable(obj) {
if (obj == undefined)
return;
if ('Array' === obj.constructor.name) {
for (var i = 0, table; i < obj.length; i++) {
table = getTable(obj[i]);
if (table && table.isValid)
return table;
}
return;
}
if (obj.constructor.name == 'Cell')
return obj.parent;
if (obj.parent.constructor.name == 'Cell')
return obj.parent.parent;
if (
obj.hasOwnProperty('cells')
&& obj.cells.length > 0
)
return obj.cells[0].parent;
if (
obj.hasOwnProperty('tables')
&& 0 !== obj.tables.length
)
return obj.tables[0];
};
