简体   繁体   English

使用JavaScript将onclick事件与参数绑定

[英]using javascript to bind onclick event with arguments

I am using javascript to create a button element and binding onclick event to it. 我正在使用javascript创建按钮元素并将onclick事件绑定到它。 I am using below code 我正在使用下面的代码

function getElement (rowObject )
       {
          var element ='<div id="deptNmBtn"><button onClick=getDepartMentNm("' +   rowObject.empName+'")> <span>Add</span></button></div>';
          return element;
       }

But here I am passing a parameter Employee Name. 但是我在这里传递了一个参数Employee Name。 The code works if employee name is passed as a single string without any spaces but when passed with spaces its throwing javascript error. 如果将员工姓名作为单个字符串传递而没有任何空格,则该代码有效,但如果使用空格传递,则会引发javascript错误。

    SyntaxError: unterminated string literal

Have anyone faced this error ? 有没有人遇到这个错误? Any help will be really appreciated. 任何帮助将不胜感激。 Thanks. 谢谢。

You need to wrap the inline click handler with ' : 您需要使用'来包装内联点击处理程序:

function getElement (rowObject) {
  var element = '<div id="deptNmBtn"><button onClick=\'getDepartMentNm("' +   rowObject.empName + '")\' ><span>Add</span></button></div>';
  return element;
}

DEMO . 演示

There is a quoting problem in your code. 您的代码中有一个引用问题。 Try this: 尝试这个:

var element = '<div id="deptNmBtn"><button onClick="getDepartMentNm(\'' + rowObject.empName + '\')" ><span>Add</span></button></div>';

As you can see, the value for onClick is unquoted. 如您所见, onClick的值未引用。 Browsers can parse unquoted attributes, but then they are expected to end up to a space. 浏览器可以解析未加引号的属性,但随后它们将以空格结尾。 Actually your parsed code looks like this: 实际上,您解析的代码如下所示:

<button onClick=getDepartMentNm("Employer Name")>

HTML parser cuts the function call from the first space, and Name") is ignored since it can't be regognized as valid HTML. JavaScript is executed from "right to left", and the first thing JS tries to do is to get a valid string for function argument. Now HTML parser has cut the function, and JS can't find closing quote, so it throws an error. HTML解析器从第一个空格处截断了函数调用,由于无法将其重新识别为有效的HTML,因此会忽略Name") 。JavaScript是从“右向左”执行的,JS要做的第一件事是获取函数参数的有效字符串,现在HTML解析器已剪切函数,而JS找不到右引号,因此会引发错误。

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

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