添加单击事件侦听器并传递参数

时间:2016-09-11 01:52:11

标签: jquery addeventlistener

我有这个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并在$("#result" + id).click(this.displayDetailView(result));foreach进行操作?

你能简单地传递结果对象吗?

1 个答案:

答案 0 :(得分: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);
}