首页 > 解决方案 > 点击功能在jquery中不起作用

问题描述

在下面的代码中,当有人单击 SELL 按钮(第一个 td)但单击功能不起作用时,我想运行一个函数。它说未定义运行功能。

function runfunction() {
  alert("success");
}

sendRequest(); //call function
function sendRequest() {
  $.ajax({
    type: "POST",
    url: '<?php echo site_url("ajax/ajax_buybtc"); ?>',
    success: function(result) {
      var jsonResult = JSON.parse(result);
      $(".tab1 tr.tr1").remove();
      jsonResult.forEach(function(data) {
        var newTr = ""; // I delete the value to avoid double tr declaration
        newTr +=
          '<tr class="tr1"> <td onclick="runfunction()" style="text-align:center;"><a><span  class="label label-warning">Sell</span></a></td>';
        newTr += "<td id='xbtc " + data.xbtc + "'>" + data.xbtc + "</td>";
        newTr += "<td id='xbtc " + data.rate + "'>" + data.rate + "</td>";
        newTr += "<td id='xbtc " + data.xpkr + "'>" + data.xpkr + "</td>";
        newTr += "</tr>";
        $(".tab1 > tbody:last-child").append(newTr);
      });

      setTimeout(function() {
        sendRequest(); //this will send request again and again;
      }, 4000);
    },
  });
}

标签: javascriptjquery

解决方案


您需要更改onclick="runfunction()"onclick="runfunction". 目前正在发生的事情是runfunction被执行,并且它的返回值被绑定到onclick事件。您希望绑定函数本身,而不是其返回值。


推荐阅读