简体   繁体   English

在我自己的js模板系统/引擎中使用jquery选择

[英]Selecting with jquery in my own js templating system/engine

For simplification and control, I have my own js templating engine, which works like this: 为了简化和控制,我有自己的js模板引擎,其工作方式如下:

html: HTML:

 <ul id="persons">
    <li class="person-template hide">
       <span>{name}</span>, <span class="placemark" data-lat="{latitude}" data-lng="{longitude}">{location}</span>
    <li>
 </ul>

js: JS:

 var persons = [
       {"name":"hulk", "location": "usa", latitude: -33.4, longitude: -70.5}, 
       {"name":"wolverine", "location": "mexico", latitude: -33.4, longitude: -70.5}, 
 ];


 $.each(persons, function(i, person) {
      var html = $(".person-template").clone().removeClass("person-template").addClass("person").show().outerHtml();

      html = html.replaceAll("{name}", person.name);
      html = html.replaceAll("{latitude}", person.latitude);
      html = html.replaceAll("{longitude}", person.longitude);
      html = html.replaceAll("{location}", person.location);
 });

( replaceAll and outerHtml are two helper functions I've made, they are self-explained by their names) replaceAllouterHtml是我制作的两个帮助器函数,它们的名称可以自解释)

My problem with this is that sometimes I want to select things with jQuery but my template notation interferes, for example: 我的问题是,有时候我想用jQuery选择内容,但是我的模板符号会干扰,例如:

$(".placemark").each(function(i, v) {
     alert($(v).data("latitude")));
});

Will alert: "{latitude}", "-33.4", "-33.4" 会提醒:“ {latitude}”,“-33.4”,“-33.4”
Obviously I want to avoid the template value. 显然我想避免模板值。

What is the most clean solution for this? 最干净的解决方案是什么?

  1. Start using a formal template engine? 开始使用正式的模板引擎?
  2. Skip first in the $.each? 先跳过$ .each吗? (kind of ugly) (有点丑)
  3. ...? ...?

You are cloning the template, so it still exists. 您正在克隆模板,因此它仍然存在。 You need to remove it after you loop through. 遍历后需要将其删除。

$(".person-template").remove();

or, you can just make sure not to grab the person-template when you alert. 或者,您可以确保在发出警报时不要抓住人员模板。 $(".location_but_not_location_template").each ... $(“。location_but_not_location_template”)。each ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM