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[].

5
  • Is geometry a string? Commented Jul 11, 2018 at 3:59
  • @CertainPerformance yes its a string. So $('geometry'+geometry+'Fields') ? Commented Jul 11, 2018 at 4:00
  • @Xufox Yea, I don't know so just made it up for the example. Commented Jul 11, 2018 at 4:01
  • Possible duplicate of 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());. Commented Jul 11, 2018 at 4:02
  • Also: Refer to a variable using a string containing its name?. Commented Jul 11, 2018 at 4:11

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

It's appropriate.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.