Select 使用函数返回的字符串预定义变量

Select predefined variable using string returned from a function

我在想,这是否可能: 我有一个带有 URL 的网页:".../product.html?id1",

并使用 Handlebars.js 我正在尝试从包含产品的 js 文件进行渲染:

$(function() {
  var id1 = {
    name: "Module 14/88",
    ID: "445856",
    desc: "some text"
  };
  var id2 = {
    name: "Kolp-display",
    ID: "445857",
    desc: "some other text"
  };
  //..... // about 60 more, but the same format
  function prid() {
    var full_url = document.URL;
    var url_array = full_url.split('?');
    var last_segment = url_array[url_array.length - 1];
    return last_segment;
  };

  var theTemplateScript = $("#template").html();
  var theTemplate = Handlebars.compile(theTemplateScript);
  $(".panel").append(theTemplate(prid())); // this does not work
});

并且模板嵌入到 HTML 中并且在我手动设置变量时工作。它总是一次只呈现一种产品,例如产品页面。

<script id="template" type="text/x-handlebars-template">
    <div class="panel-heading">
        <h2><span>{{name}}</span></h2>
        <p><span>{{ID}}</span></p>
    </div>
    <div class="container-fluid">
        <div class="row" style="margin-top: 2rem">
            <div class="col-sm-7 ">
                <p>{{desc}}</p>
            </div>
        </div>
    </div>
</script>

所以本质上,我试图 select 一个要从 URL 中的 id 呈现(附加)的变量,以包含在以下部分中:

$(".panel").append(theTemplate(___selected_variable_from_id_in_URL___));

所以在这种情况下 prid() 返回的值是 id1,所以我希望 id1 数组被 Handlebars 使用。 由于变量已定义,我只想使用 prid() 函数中的字符串作为变量的标识符。 有没有办法做到这一点,我不知道,到目前为止搜索也没有帮助。

根据您当前拥有的代码,您需要使用 eval

首选方法是将整个数据集作为单个对象的一部分,其中 id 是键,数据是相应 ID 的值。

var data = {
  id1: {
    name: "Module 14/88",
    ID: "445856",
    desc: "some text"
  },
  id2: {
    name: "Kolp-display",
    ID: "445857",
    desc: "some other text"
  }
};

那么您只需 data[prop()] 即可提取正确的数据集。

我不推荐的其他方法是将变量存储为 window 对象的一部分或使用 eval。

正在从全局范围访问对象

// or declare them in the global scope, which can then be accessed 
// from the same object
window.id1 { name:"Module 14/88", ID:"445856", desc:"some text" };
window.id2 { name:"Kolp-display", ID:"445857", desc:"some other text" };

window[prop()]

这会在全局命名空间中引入变量泄漏。最好避免使用全局变量。

使用评估

eval(prop())