简体   繁体   中英

click event without any response

i got an asp.net mvc project, but actually most of functions i achieved via javascript, below screenshot is the part which makes me frustrating, here you can see i use a date picker to define time slot then filter content for next dropdown button with related contents.

在此处输入图片说明

 $('.input-daterange').datepicker({
                    format: "yyyymm",
                    minViewMode: 1,
                    language: "zh-CN",
                    beforeShowMonth: function (date) {
                        switch (date.getMonth()) {
                            case 0:
                                return false;
                            case 1:
                                return false;
                            case 2:
                                return false;
                            case 3:
                                return false;
                            case 4:
                                return false;

                        }
                    }
                }).on('changeDate', function (e) {
                    var from = $('#from-date').val();
                    var to = $('#to-date').val();
                    if (from !== to) {
                        $.ajax({
                            type: "GET",
                            url: "DataChanged?fromDate=" + $('#from-date').val() + "&toDate=" + $('#to-date').val(),
                            dataType: "json"
                        })
                            .done(function (data) {
                                //var legth = data.chart.length;
                                $('#brandtable').empty();
                                var contents = $.parseJSON(data);
                                $.each(contents, function (key, values) {
                                    $.each(values, function (k, v) {
                                        $('#brandtable').append("<td><button class='btn btn-default' id=" + v.ID + ">" + v.BrandName + "</button></td>");

                                        if (k % 9 === 0) {

                                            if (k !==0) {
                                                $('#brandtable').append("<tr></tr>");
                                            }
                                        }
                                    });

                                });


                            });

                    };


                });




        });

Ok now, everything is fine, content was added successfully with button tag, but now i want click on button to get data from server just like above action, it is very strange that click event doesn't work, i don't know why? i did it in this way,

 @foreach (var item in Model)
                {
                    <text>
                          $("#@item.ID").click(function () {
                              $.getJSON("@Url.Action("ReturnContentForSrpead", new { @ID = item.ID })", function (msg) {
                                  var tags = BID.getParams.C32().tags;
                                  var data = (msg.data || {}).wordgraph || [{ key: tags[0] }, { key: tags[1] }, { key: tags[2] }, { key: tags[3] }, { key: tags[4] }];
                                  iDemand.drawBg().setData(data[lastTab]).drawCircle(BID.getColor(lastTab)).wordgraph = data;
                              });

                          });
                    </text>
                }

i passed all instances from controller when i render page at very beginning, so that means all content already got, but only use jquery ajax to achieve kind of asynchronous. if you confuse with why i used Razor to render scripts, ok, i tried javascript as well, but got same result.

but one thing makes me shake was, when i run below code from console, it works fine.

  $("#@item.ID").click(function () {
             console.log('clicked');                  

                          });

Do not render inline scripts like that. Include one script and add a class name to the dynamically added elements and store the items ID as a data- attribute, then use event delegation to handle the click event

In the datepickers .on function

var table = $('#brandtable'); // cache it

$.each(values, function (k, v) {
  // Give each cell a class name and add the items ID as a data attribute
  table .append("<td><button class='btn btn-default brand' data-id="v.ID>" + v.BrandName + "</button></td>");

Then use event delegation to handle the click event.

var url = '@Url.Action("ReturnContentForSrpead")';
table.on('click', '.brand', function() {
  // Get the ID
  var id = $(this).data('id');
  $.getJSON(url, { ID: id }, function (msg) {
     ....
  });
});

Side note: Its not clear what your nested .each() loops are trying to do and you are creating invalid html by adding <td> elements direct to the table. Best guess is that you want to add a new rows with 9 cells (and then start a new row) in which case it needs to be something like

$.each(values, function (k, v) {
  if (k % 9 === 0) {
    var row = $('</tr>');
    table.append(row);
  }
  var button = $('</button>').addClass('btn btn-default brand').data('id', v.ID).text(v.BrandName);
  var cell = $('</td>').append(button);
  row.append(cell);
})

Recommend also that you change

url: "DataChanged?fromDate=" + $('#from-date').val() + "&toDate=" + $('#to-date').val(),

to

url: '@Url.Action("DataChanged")',
data: { fromDate: from, toDate: to }, // you already have the values - no need to traverse the DOM again

You are binding click event on every item ID but the way you are getting id is not right. This $("#@item.ID") will not find any element because this will bind click to an element whose id is @item.ID and there is no such element will this id. You need to change it like below. Concatenate "#" with each item id.

$("#"+@item.ID).click(function () {
//your code
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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