2016-09-11 61 views
0

我有這個jQuery函數,它爲每個搜索結果顯示一張卡片並附帶一些關於結果的信息。添加點擊事件監聽器並傳遞參數

我希望能夠點擊卡片並調出一個對話框,其中將詳細顯示結果。

如何添加將結果作爲參數傳遞的click event listener以便我可以在結果詳細信息對話框中使用結果?

displayResults() { 
    $('#result-cards').empty(); 
    var id = 0; 
    this.results.forEach(result => { 
     $('#result-cards').append(` 
     <div class="col-sm-6 col-md-4 col-xl-3 product-item-container"> 
     <div class="form-group product-item scale-on-hover"> 
       <div class=""> 
      <div class=""> 
         <div class="image" id="image` + id + `"></div> 
      </div> 
        <div id="info"> 
      <h6 id="brand">` + result.brand + `</h6> 
         <h6 id="name">` + result.name + `</h6> 
      <hr> 
        </div> 
       </div> 
     </div> 
      </div> 
     ` 
    ); 
     $('#image' + id).css("background", result.image); 
     id++; 
    }); 
    this.padding = "10px 0px 50px 0px"; 
    this.height = "inherit"; 

    } 

喜歡的東西給每個結果卡中的id和foreach內做$("#result" + id).click(this.displayDetailView(result));

你能簡單地傳遞結果對象嗎?

回答

0

由於this SO answer狀態,你可以使用這個語法來設置了一個param傳遞給Click事件處理程序:

// say your selector and click handler looks something like this... 
$("some selector").click({param1: "Hello", param2: "World"}, cool_function); 

// in your function, just grab the event object and go crazy... 
function cool_function(event){ 
    alert(event.data.param1); 
    alert(event.data.param2); 
} 

我的代碼:

displayResults() { 
    $('#result-cards').empty(); 
    var id = 0; 
    this.results.forEach(result => { 
     $('#result-cards').append(` 
     <div id="result` + id + `" class="col-sm-6 col-md-4 col-xl-3 product-item-container"> 
      <div class="form-group product-item scale-on-hover"> 
        <div class=""> 
       <div class=""> 
         <div class="image" id="image` + id + `"></div> 
       </div> 
         <div id="info"> 
        <h6 id="brand">` + result.brand + `</h6> 
          <h6 id="name">` + result.name + `</h6> 
        <hr> 
         </div> 
        </div> 
      </div> 
     </div> 
    ` 
     ); 
     $('#image' + id).css("background", result.image); 
     $("#result" + id).click({ result: result }, this.resultClick); 
     id++; 
    }); 
    this.padding = "10px 0px 50px 0px"; 
    this.height = "inherit"; 
} 

resultClick(event) { 
    console.log(event.data.result); 
}