jQuery动态生成a标签时无法正确设置URL查询字符串值问题求助
问题原因
拼接a标签的href属性时引号位置错误,你在/Controller/Detail/?Id=后面提前写了闭合的引号,直接把href属性提前结束了,后续拼接的customer.EventId被浏览器识别成了独立的无效属性,最终就出现了你看到的多余"1=""的异常输出。
修正方案
把href属性的闭合引号挪到customer.EventId的后面即可,修改后的代码如下:
$.each(model.data, function () { var customer = this; var event = customer.Event; // 仅修改aTag这一行的引号位置即可 var aTag = '<a href="/Controller/Detail/?Id=' + customer.EventId + '" class="ReportableEve text-primary" title="Details">' + event + '</a>'; $("td", row).eq(0).html(aTag); $("td", row).eq(1).html(customer.VesselName); $("td", row).eq(2).html(customer.VesselType); $("td", row).eq(3).html(customer.EventType); $("td", row).eq(4).html(customer.EventDate); $("td", row).eq(5).html(customer.Severity); $("td", row).eq(6).html(customer.Status); $("td", row).eq(7).html(customer.Assignee); $("td", row).eq(8).html(customer.BriefDescription); $("#ReportableEventGrid").append(row); row = $("#ReportableEventGrid tbody tr:last-child").clone(true); });
优化建议
为了避免后续再出现类似的引号匹配错误,推荐直接用jQuery的元素创建API生成DOM,代码更易读也更安全:
var aTag = $('<a>', { href: '/Controller/Detail/?Id=' + customer.EventId, class: 'ReportableEve text-primary', title: 'Details', text: event }) // 后续直接把aTag元素插入到td即可,不需要再用html方法传入字符串 $("td", row).eq(0).empty().append(aTag);
内容的提问来源于stack exchange,提问作者Developer
相关产品推荐
相关产品推荐

