[英]passing parameters in anchor tag onclick event
I'm creating anchor tag dynamically like 我正在动态创建锚标签
for (var i = 0; i < json.length; i++)
{
<td><a href='#' id=" + json[i].id + " onclick=getId('" + json[i].id + "','"+ json[i].text +"')>" + json[i].text + " </a></td>
}
and In the onclick
function I have defined like 在
onclick
函数中,我定义为
function getId(ID,text)
{
console.log(ID);
console.log(text);
}
In this onclick
event If the text value doesn't contain any space or gap between word to word, I'm able to get the text value in console, In-case If text contains any spaces then It is showing error like Unexpected token ILLEGAL
. 在此
onclick
事件中,如果文本值在单词与单词之间不包含任何空格或空格,我可以在控制台中获取该文本值,以防万一如果文本包含任何空格,则显示错误,例如Unexpected token ILLEGAL
。
<a href='#' id=" + json[i].id + " onclick=getId('" + json[i].id + "','"+ json[i].text +"')>" + json[i].text + " </a>
Above code might work, but IMHO its not good practice. 上面的代码可能有效,但是恕我直言,它不是一个好习惯。
Try this, I prefere it this way and much cleaner. 试试这个,我更喜欢这样,而且更干净。
var a = document.createElement('a');
a.setAttribute('id',json[i].id);
a.setAttribute('href',"#");
a.innerHTML = json[i].text;
a.onclick = function(e) {
getId(json[i].id, json[i].text);
e = e || window.event;
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
return false;
};
It is possible that your text value could have an invisible character that causes the Unexpected token ILLEGAL
. 您的文本值可能具有不可见的字符,从而导致
Unexpected token ILLEGAL
。
No visible cause for "Unexpected token ILLEGAL" should explain more on ILLEGAL characters. 没有明显的原因导致“意外的令牌非法”应该对非法字符进行更多说明。
Remove zero-width space characters from a JavaScript string could help you try to remove these characters. 从JavaScript字符串中删除零宽度空格字符可以帮助您尝试删除这些字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.