简体   繁体   English

单击功能在jQuery中不起作用

[英]on click funtion is not working in jquery

In following code i want to run a function when someone click on SELL button(first td) but on click function is not working. 在下面的代码中,当有人单击“卖出”按钮(第一次td)但单击功能不起作用时,我想运行一个功能。 it says run function is not defined. 它说运行功能未定义。

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);
    },
  });
}

You need to change onclick="runfunction()" to onclick="runfunction" . 您需要将onclick="runfunction()"更改为onclick="runfunction" Currently what's happening is that the runfunction is executed, and its return value is bound to the onclick event. 当前发生的事情是runfunction已执行,其返回值绑定到onclick事件。 You want the function itself to be bound, not its return value. 您想绑定函数本身,而不是返回值。

newTr += '<tr class="tr1"> <td onclick="runfunction()" style="text-align:center;"><a><span  class="label label-warning">Sell</span></a></td>';

move onclick to span tag 移动onclick以跨度标记

newTr += '<tr class="tr1"> <td style="text-align:center;"><a><span onclick="runfunction()"  class="label label-warning">Sell</span></a></td>';

https://codepen.io/bot_3310/pen/JajYyY https://codepen.io/bot_3310/pen/JajYyY

try to add a click function after adding a class (here I added 'td-click') to the td and remove the onclick attribute from td 尝试在将类(此处添加了“ td-click”)添加到td之后添加click函数,并从td中删除onclick属性

$(".tab1").on("click", ".td-click", function(){
   alert("success");
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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