在从Javascript追加的onclick函数中传递参数

时间:2019-01-02 11:59:42

标签: javascript jquery

我有一段类似于下面的代码,

$(document).ready(function(){
  var agr1='#19865 - testArg';
  var arg2=1856
  $('#dv_Test').append('<button onclick="testFunction('+ agr1 +','+ arg2 +')">Test</button>')
});
function testFunction(arg1, arg2) { 
  alert(arg1);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dv_Test"></div>

在这里出现如下错误

testFunction(#19865 - testArg,1856)  
  

未捕获的SyntaxError:无效或意外的令牌

我的字符串agr1本身没有""

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:5)

问题是因为using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Kadaster.NewsLetters.DomainModel; namespace WpfApplication { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public string hoi => "yYy"; public MainWindow() { DataContext = this; InitializeComponent(); } } } 值是一个字符串,并且需要用引号引起来:

arg1
$(document).ready(function() {
  var agr1 = '#19865 - testArg';
  var arg2 = 1856
  $('#dv_Test').append('<button onclick="testFunction(\'' + agr1 + '\',' + arg2 + ')">Test</button>')
});

function testFunction(arg1, arg2) {
  alert(arg1);
}

然而更好的方法是将这些值放在<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="dv_Test"></div>属性中,并添加一个委托事件处理程序来处理所有动态创建的按钮。试试这个:

data
$(document).ready(function() {
  var agr1 = '#19865 - testArg';
  var arg2 = 1856
  var $div = $('#dv_Test').append('<button data-arg1="' + agr1 + '" data-arg2="' + arg2 + '">Test</button>');
  
  $div.on('click', 'button', function() {
    var $btn = $(this); 
    console.log($btn.data('arg1'), $btn.data('arg2'));
  }); 
});

答案 1 :(得分:1)

您需要在参数周围加上引号。或者,您也可以尝试使用模板文字

$(document).ready(function() {
  var agr1 = '#19865 - testArg';
  var arg2 = 1856
  $('#dv_Test').append(`<button onclick="testFunction('${agr1}','${arg2}' )">Test</button>`)
});

function testFunction(arg1, arg2) {
  alert(arg1);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dv_Test"></div>