2016-06-07 6 views
0

Backbonejs를 공부하고 있습니다. handlebars.js로 추가 한 동적 요소에 문제가 있습니다. HTML클릭 이벤트 백본에서 동적 HTML 요소 검색

<section class="single-item"> 
    {{#each [0]}} {{#if name}} 
    <div class="card col s12"> 
     <form action="/productdetail" id="product-form"> 
      <div id="dettagliofromhomepage" class="card-image"> 
       {{#if img}} 
       <img id="imgslide" src="{{img}}" data-prod="{{id}}"> {{else}} 
       <img id="imgslide" src="img/no.jpg" data-prod="{{id}}"> {{/if}} 
      </div> 
      <div id="card-border" class="col s12"> 
       <div class="card-content col s6"> 
        <p class="productTitle">{{name}} 
         <br> €{{price}} 
        </p> 
       </div> 
       <div class="card-action col s6 "> 
        <a id="bottone-ca" class="waves-effect waves-light btn light-green darken-3"><i class="material-icons">add_shopping_cart</i></a> 
       </div> 
      </div> 
     </div> 
     {{/if}} {{/each}} 
    </section> 

내가 출력 앵커 "bottone-CA"클릭에 대해서는 "단일 항목"의 요소의 값을 원하는 : 이것은 내 HTML 코드입니다. 나는. 클래스 "카드 콘텐츠"에서 <p>의 값을 가져 오려고합니다. 동적으로 "each"구조를 사용하여 5 개의 요소를 추가합니다. 그러나 js에 연산자 "this"를 사용하려고하면 내가 추가 한 항목의 첫 번째 요소를 출력으로 가져올 수 있습니다. 이 내 JS 스 니펫입니다 :

define(function(require) { 

var $ = require("jquery"); 
var Backbone = require("backbone"); 
var Products_homepage = require("models/Products_homepage"); 
var Products = require("models/Products"); 
var MyCollection = require("collections/Categories"); 
var localizzatoreView = require("views/pages/localizzatoreView"); 
var Utils = require("utils"); 
var productHomepage = require("models/productHomepage"); 
var onlineProduct = require("models/onlineProduct"); 
var saleProduct = require("models/saleProduct"); 


var MyView = Utils.Page.extend({ 
    constructorName: "MyView", 
    model: Products_homepage, 

    initialize: function() { 
     this.template = Utils.templates.myview; 
    }, 

    id: "myview", 
    className: "i-g page", 

    events: { 
     "click #imgslide": "prodotto", 
     "click #bottone-ca": "carrello" 
    }, 

    render: function() { 

     var that = this; 

     var online = new onlineProduct(); 
     var sale2 = new saleProduct(); 
     var arraytest = []; 
     var loca= localStorage.getItem("localizzazione"); 

     online.fetch({ 
      success: function() { 

       arraytest[0]=(online.attributes); 
       test= online.attributes; 


       sale2.fetch({ 
        success: function() { 

         $(that.el).html(that.template(arraytest)); 

         that.startslider(); 
         that.startnav(); 

         return that; 
        } 
       }); 
      } 
     }); 

    }, 

    carrello: function(e) { 
     var arraytemp = []; 
     arraytemp = localStorage.getItem("Carrello"); 

     var idprod = $('#id_prodotto').val(), 
     name = $("#name").val(), 
     img = $("#img").val(), 
     price = $("#price").val(), 
     quantity = 1; 

     /*Here i want to retrieve element that i clicked */ 

     var prod = new Products({ 
      name: name, 
      id: idprod, 
      img: img, 
      price: parseFloat(price).toFixed(2), 
      quantity: quantity, 
      total: price * quantity 
     }); 

     var Carrello = JSON.parse(localStorage["Carrello"]); 
     Carrello.push(prod); 
     localStorage["Carrello"] = JSON.stringify(Carrello); 

     Backbone.history.navigate("basket", { 
      trigger: true 
     }); 

    } 
}); 

죄송합니다 사전에 미리 어떤 오류. JavaScript와 백본에 익숙하지 않습니다. 도움에 미리 감사드립니다. Stack Overflow를 배우는 도구로 사용하고 있습니다.

+0

여러 제품 양식 (# product-form)을 페이지에 렌더링하는 템플릿이 있습니까? 그렇다면 중복 된 요소 ID가 많이 생깁니다. 유효하지 않은 HTML입니다. – 76484

답변

1

id 선택자를 사용하고 있으므로 항상 $('#id_prodotto')과 같은 글로벌 선택기의 첫 번째 요소를 가져옵니다. id은 전체 문서에서 고유해야하며 브라우저는 첫 번째 일치 항목을 반환합니다. 동적 템플릿에서는 정적 인 id을 사용하지 않아야합니다. CSS 클래스 또는 다른 속성을 대신 사용하십시오.

는 예를 $(event.currentTaget).closest('#card-border').find('p').text()를 들어, id을 갖는 가장 가까운 요소를 반환 있도록 이벤트 대상에 관련된 DOM을 $(event.currentTaget); 같은 이벤트 객체를 통해 현재 요소에 액세스하고 조회 할 수 있습니다, 말했다.

그러나 동일한 요소가 여러 개있는 것은 바람직하지 않습니다. id.