简体   繁体   English

javascript函数调用字符串中的括号

[英]Parentheses in string of javascript function call

I have a loop that creates links with a javascript function call in the onClick events and uses the text returned from a database as one of the parameters. 我有一个循环,该循环在onClick事件中创建带有javascript函数调用的链接,并将从数据库返回的文本用作参数之一。 My issues I am having is that sometimes this text being returned has parenthesis in them which is causing a syntax error in my code. 我遇到的问题是,有时返回的文本中带有括号,这在我的代码中导致语法错误。 Example: 例:

code:
formResults += "<a onclick='openForm(" + this.displayText + "," + this.ID + ");'>" + this.displayText + "</a>";

HTMLDisplay:
<a onclick="openForm(Example Form (Example Form 1) Application Instructions ,1108);">Example Form (Example Form 1) Application Instructions </a>

as you can see the name of the form contains a set of parenthesis. 如您所见,表单名称包含一组括号。 Is there anyway I can include these? 无论如何,我可以包括这些吗? The reason I need to is because the function points to another system that uses the ID and displayText in order to render the proper form. 我需要的原因是因为该函数指向另一个系统,该系统使用ID和displayText来呈现正确的格式。 thank you 谢谢

The parenthesis aren't the problem, it's the lack of quotes inside the function. 括号不是问题,这是函数内部缺少引号。

formResults += "<a onclick='openForm(\'" + this.displayText + "," + this.ID + "\');'>" + this.displayText + "</a>";

This below snippet (from yours) 下面的摘录(来自您的)

`openForm(Example Form...`)

Will throw an error because it's looking for variables Example and so on, quote that string! 因为正在寻找变量Example等等,所以将引发错误,引用该字符串!

I strongly suggest 我强烈建议

code: 码:

formResults += '<a class="openForm" data-text="'+this.displayText + '" id="'+this.ID + '">' + this.displayText + '</a>';

HTMLDisplay: HTMLDisplay:

<a class="openForm" data-text="Example Form (Example Form 1) Application Instructions" id="1108">Example Form (Example Form 1) Application Instructions </a>

jQuery: jQuery的:

$(function() {
  $(".openForm").on("click",function(e) {
    e.preventDefault();
    openForm($(this).data("text"),this.id);
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM