在我的C#代码中,我正在生成动态HTML并希望传递参数。所以我尝试了这个:
var CityName = "Barcelona";
var Id = 3;
myHtml = "<a onclick='increaseLikes(" + Id + ",'" + CityName + "')'>";
但它的呈现方式如下:
<a onclick="increaseLikes(4," href="#" Barcelona')'="">
如何更改代码以生成有效的HTML和JS?
答案 0 :(得分:2)
在创建html时需要使用双引号。
像..
function ddiff() {
var txtfromdate = document.getElementById('<%=txtPeriodFrom.ClientID%>').value;
var txttodate = document.getElementById('<%=txtPeriodTo.ClientID%>').value;
alert(txtfromdate);
var oneDay = 1000 * 60 * 60 * 24; //Convert into millisec
var firstDate = $.datepicker.formatDate("dd-mm-yyyy", txtfromdate);
var secondDate = $.datepicker.formatDate("dd-mm-yyyy", txttodate);
alert(firstDate);
alert(secondDate);
var noOfDays = Math.ceil((secondDate.getTime() - firstDate.getTime()) / oneDay);
return noOfDays;
}
所以你的输出将是
string myHtml = "<a onclick='increaseLikes(" + Id + ",\"" + CityName + "\")'>";
答案 1 :(得分:2)
假设您希望<a onclick='increaseLikes(3,"Barcelona")'>
您可以更改
行myHtml = "<a onclick='increaseLikes(" + Id + ",'" + CityName + "')'>";
到
myHtml = string.Format(@"<a onclick='increaseLikes({0}, ""{1}"")'>", Id, CityName);
答案 2 :(得分:1)
您应该正确关闭锚标记。
string myHtml = "<a href=\"#\" onclick=\"increaseLikes(" + Id + ",\'" + CityName + "');\">...</a>";