如何在 jquery onclick 中传递多个参数

How to pass multiple parameter in jquery onclick

$(document).ready(function () {
var from='2022-02-21';
var to='2022-02-25';
var category ='rt';
var btndiv = '<div class="col-12 text-right">\
               <input type="button" value="Generate Invoice" id="btngenerateinvoice" onclick="generateinvoice('+ from + ',' + to + ',' + category + ')" class="btn btn-blue btn-sm" /></div>';
    $(".btndiv").append(btndiv);
});


function generateinvoice(ff, tt, cc) {
    alert("helo");
    var f = ff;
    var t = tt;
    var c = cc
    
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row btndiv">
                                
</div>

我在 onclick generateinvoice 函数上动态传递了三个参数,但是 generateinvoice 这些函数没有被调用

问题是 onclick="generateinvoice 中的值在呈现时,代码认为它是变量,而这些值尚未定义。您可以在每个变量前后添加\'

所以你可以onclick="generateinvoice(\''+ from + '\',\'' + to + '\',\'' + category + '\')"

如果没有 \',呈现的代码可能看起来像 generateinvoice(from,to,category),但是当您添加这些代码时,代码会将变量呈现为字符串,所以它看起来像 generateinvoice('from','to','category')

演示

$(document).ready(function() {
  var from = "f",
    to = "t",
    category = "cc";

  var btndiv = '<div class="col-12 text-right">\
               <input type="button" value="Generate Invoice" id="btngenerateinvoice" onclick="generateinvoice(\''+ from + '\',\'' + to + '\',\'' + category + '\')" class="btn btn-blue btn-sm" /></div>';
  $(".btndiv").append(btndiv);
});


function generateinvoice(ff, tt, cc) {
  alert("helo");
  var f = ff;
  var t = tt;
  var c = cc

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row btndiv">

</div>