简体   繁体   English

如何从HTML将字符串传递给Javascript函数?

[英]How to pass a string to the Javascript function from HTML?

I have a dynamic Html table in which there is a cell that contains anchor tag. 我有一个动态的HTML表格 ,其中有一个包含锚标记的单元格。 Along with the anchor tag, I'm calling a function thru OnClick method. 与锚标记一起,我通过OnClick方法调用一个函数。 That function takes two parameter and both are String type. 该函数有两个参数,并且都是String类型。

In that, one string contains the value like this "PUT Request|GET Request|JDBC Request|" 其中,一个字符串包含类似“ PUT请求| GET请求| JDBC请求|”的值。

Example: 例:

<td align='center'><a href='#' title='click here' onclick=showTestCaseReport('" 
+ tcId + "','" + strStep + "')>Detail</a></td>

JavaScript function: JavaScript函数:

function showTestCaseReport(testCaseId, testSteps)
{
    alert(testCaseId);
    alert(testSteps);
}

But when click on the click ie Detail from the browser, Javascript alert is not displaying as per the function defined. 但是,当从浏览器中单击“单击即详细信息 ”时,不会按照定义的功能显示Javascript警报。

EDITED: After analysed, I came to know that the String value that I had mentioned above has white space in the middle. 编辑:经过分析,我知道上面提到的String值中间有空格。 After removing the white spaces like this PUTRequest|GETRequest|JDBCRequest| 除去这样的空白后, PUTRequest | GETRequest | JDBCRequest | , its working. ,其工作。

Ques: Is there any way to handle this without removing the white space in the middle of the string values? 问题:是否有任何方法可以在不删除字符串值中间的空白的情况下进行处理?

Thanks 谢谢

您的onclick属性缺少引号,请正确添加引号并继续进行操作参见此https://jsbin.com/viqosobizo/edit?html,输出

<td align='center'><a href='#' title='click here' onclick="showTestCaseReport('hello','great');">Detail</a></td>

You are not showing how you create that table. 您没有显示如何创建该表。 Assuming you have your <td> wrapped in quotes too, you need to either escape them or use data attributes (recommended) 假设您也将<td>用引号引起来,则需要转义或使用数据属性(推荐)

"<td align='center'><a href='#' title='click here'"+
" data-tcId='"+tcId+"' data-strStep='"+strStep+"'"+ 
" onclick='return showTestCaseReport(this)'>Detail</a></td>"

Then 然后

function showTestCaseReport(cell) {
  var testCaseId = cell.getAttribute("data-tcId"),
      testSteps  = cell.getAttribute("data-strStep");
  ....
  return false; // cancel link
}

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

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