如何在onClick函数中传递JavaScript变量

时间:2016-11-05 09:25:32

标签: javascript onclick

这是我的代码,我想在点击功能中获取元素信息,就像我的注释所说的那样。

for(var i = 0, len = json.length; i < length; i++) {
  var curid = json['success'][i]['courier_id'];
  var curname = json['success'][i]['courier_name'];
  document.getElementById("gsid").value=curname;                    
  var tr="<tr>&nbsp;&nbsp;";

  //here is where i want to use onclick function with curid and curname 
  var td1="<td>"+"<input type='radio' name='as' value='json['success'][i]['courier_id']' id='curiid' onclick='courierselect(<?php echo $shyam='\'+curname+\''; ?>);'/>"+"</td>&nbsp;&nbsp;";
  var td2="<td id='curnname'>"+json['success'][i]['courier_name']+"</td>&nbsp;&nbsp;";
  var td3="<td>"+json['success'][i]['country_charge']+"</td>&nbsp;&nbsp;";
  var td4="<td>"+json['success'][i]['estimate_delivery_time']+"</td>&nbsp;&nbsp;";
  var td5="<td>"+json['success'][i]['tracking_available']+"</td></tr>&nbsp;&nbsp;";
  $("#results").append(tr+td1+td2+td3+td4+td5); 
}

1 个答案:

答案 0 :(得分:0)

我发现您的代码存在三个问题

  • ... value='json['success'][i]['courier_id']' ...

你没有用字符串

来完成变量
  • ... courierselect(<?php echo $shyam='\'+curname+\''; ?>) ...

    1. echo $shyam='\'+curname+\'';您无法使用JS值设置PHP变量。 Understand why
    2. echo字符串值,因此您必须在curname附近添加一些引号
for(var i = 0, len = json.length; i < length; i++) {
  var curid = json['success'][i]['courier_id'];
  var curname = json['success'][i]['courier_name'];
  document.getElementById("gsid").value = curname;

  $("#results").append('<tr>&nbsp;&nbsp;');
  $("#results").append('<td><input type="radio" name="as" value="' + curid + '" id="curiid" onclick="courierselect(\'' + curname + '\');"/></td>&nbsp;&nbsp;');
  $("#results").append('<td id="curnname">' + curname + '</td>&nbsp;&nbsp;');
  $("#results").append('<td>' + json['success'][i]['country_charge'] + '</td>&nbsp;&nbsp;');
  $("#results").append('<td>' + json['success'][i]['estimate_delivery_time'] + '</td>&nbsp;&nbsp;');
  $("#results").append('<td>' + json['success'][i]['tracking_available'] + '</td></tr>&nbsp;&nbsp;');
}