0
var $geometryPointFields = $('[class*="Point"]', $panel),
    $geometryLineFields = $('[class*="Line"]', $panel),
    $geometryPolygonFields = $('[class*="Polygon"]', $panel);

function(geometry) {
    // geomtery is either Point, Line or Polygon
    ${'geometry'+geometry+'Fields'}.show() // ?
}

How do I do this? I can't or rather don't want to use window[] or scope[].

eozzy
  • 66,048
  • 104
  • 272
  • 428
  • Is `geometry` a string? – CertainPerformance Jul 11 '18 at 03:59
  • @CertainPerformance yes its a string. So `$('geometry'+geometry+'Fields')` ? – eozzy Jul 11 '18 at 04:00
  • @Xufox Yea, I don't know so just made it up for the example. – eozzy Jul 11 '18 at 04:01
  • Possible duplicate of [Use dynamic variable names in JavaScript](https://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript). You never need or want unknown variable names. Please use an object instead: `const geometries = {$geometryPointFields: $('[class*="Point"]', $panel), $geometryLineFields: $('[class*="Line"]', $panel), `…`}; console.log(geometries["geometry" + geometry + "Fields"].show());`. – Sebastian Simon Jul 11 '18 at 04:02
  • Also: [Refer to a variable using a string containing its name?](https://stackoverflow.com/q/1664282/4642212). – Sebastian Simon Jul 11 '18 at 04:11

2 Answers2

3

Because the three variables are all geometry fields, it would probably make the most sense to use an object rather than three standalone variables:

const geometryFields = {
  Point: $('[class*="Point"]', $panel),
  Line: $('[class*="Line"]', $panel),
  Polygon: $('[class*="Polygon"]', $panel)
};

Then you can access the property of the object with the geometry string:

function showGeom(classStr) {
  geometryFields[classStr].show();
}

If you have to use standalone variables, you could eval, but you really shouldn't eval:

$geometryPointFields = $('.point');
function showGeom(classStr) {
  eval('$geometry' + classStr + 'Fields').show();
}
setTimeout(() => showGeom('Point'), 1500);
.point { display: none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="point">point</div>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

Your variables are formed using jQuery selectors' response. Why don't you select and show the elements directly in the function?

function showElements(geometry) {
  $('[class*="' + geometry + '"]', $panel).show();
}

You just need to ensure that $panel is accessible in this function, and it should work fine.

31piy
  • 23,323
  • 6
  • 47
  • 67