【问题标题】:How to assign local variable in Jquery template如何在 Jquery 模板中分配局部变量
【发布时间】:2019-07-22 10:28:27
【问题描述】:

下面,我正在尝试使用 Jquery 模板打印替换的项目。在那里我想设置一个变量 partHasBeenReplaced ,稍后我可以用它来打印标签并关闭<span> 元素。

  1. 如何在那里设置变量?
  2. 如何找到“替换”类型的最后一个元素?它可能不是数组的最后一个元素。

                {{each(i,ref) productReferences}}
                        {{if ref.referenceType == 'REPLACEMENT'}}
                            {{partHasBeenReplaced = 'true'}}
                        {{/if}}
                {{/each}}
    
                {{if partHasBeenReplaced == 'true'}}
                    <span class="text-danger font-weight-bold pt-2">
                        This item has been replaced with:
                {{/if}}
    
                {{each(i,ref) productReferences}}
                        {{if ref.referenceType == 'REPLACEMENT'}}
                            {{= ref.target.code}} ,
                        {{/if}}
                {{/each}}
    
                {{if partHasBeenReplaced == 'true'}}
                    </span>
                {{/if}}
    

【问题讨论】:

  • 我通常的做法是预先对数据进行排序/过滤,因此模板包含尽可能少的逻辑。你能创建一个minimal reproducible example吗?
  • 我只是想知道,设置局部变量是否可行?
  • 我不知道,你能把我们链接到你正在使用的 jquery 模板库文档吗?从this来看,你不能。
  • 是的,只是看起来像那样
  • 其他方式是我可以从服务器设置productReferences,所以这里我只需要输入if条件。

标签: javascript jquery jquery-templates


【解决方案1】:

为了使用此类模板将数据分配给元素,最好使用属性。我们可以使用 JavaScript 访问创建/更新/删除属性。

例如,如果您想为&lt;span&gt; 添加数据,那么您可以使用 -

<span id="mySpan" class="text-danger font-weight-bold pt-2" partreplaced="{{partHasBeenReplaced}}" ></span>

可以使用下面的方法在 JavaScript 中访问 -

let span = document.querySelector("#mySpan");
let partreplaced = span.getAttribute('partreplaced');

console.log(partreplaced); //will print which was set in that attribute using the templating engine.

【讨论】:

  • 如何设置{{partHasBeenReplaced}} 值?如果我能够设置该变量,那么一切都会排序。看来,在模板中设置局部变量并不像 JSTL 那样简单。
  • 我认为你必须添加这个语法"&lt;c:out value='${partHasBeenReplaced}'/&gt;"
  • 如果您看到我的代码,我正在尝试在模板中创建变量“partHasBeenReplaced”以便我可以使用它。如果它来自服务器,那很容易。
【解决方案2】:

没有像我们在 JSTL 中那样设置局部变量的简单解决方案。所以我所做的是我使用 JS 来填充像 partHasBeenReplaced 这样的最终标志,并将其设置为数据,然后再将其传递给 Jquery 模板。这样我就可以直接使用模板中的变量了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    • 2012-01-21
    • 2016-08-07
    相关资源
    最近更新 更多