将带有空格字符的字符串作为参数传递给 javascript 生成的点击函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14232135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:05:45  来源:igfitidea点击:

Passing string with space character as parameter to on-click function generated by javascript

javascripthtml

提问by Lasang

My hypertlink generated by JavaScript is as follows:

我的JavaScript生成的超链接如下:

'<a href="#" onClick=passSearchTerm("' +aa + '");>View</a>' 
'<a href="#" onClick=passSearchTerm("' +aa + '");>View</a>' 

The parameter passes wells when the string is as follows:

字符串如下时参数pass wells:

var aa = 'TAGS(\"ab\")'; 
var aa = 'TAGS(\"ab\")'; 

I confirmed it by alerting inside the function

我通过在函数内部发出警报来确认它

function passSearchTerm(aa) { alert(aa); }

功能 passSearchTerm(aa) { 警报(aa); }

However, this wont alert when the var is defined as follows:

但是,当 var 定义如下时,这不会发出警报:

var aa = 'TAGS(\"a b\")'; //space between "a" and "b"

var aa = 'TAGS(\"ab\")'; //“a”和“b”之间的空格

Can anyone suggest me how to pass such string? Thanks in advance for your help. Actually I am trying to pass likely following string:

谁能建议我如何传递这样的字符串?在此先感谢您的帮助。实际上,我正在尝试传递可能的以下字符串:

TAGS("a or b")

标签(“a 或 b”)

回答by Nitesh Patil

While generating ur hyperlink by javascript use encodeURIComponent ex.

通过 javascript 生成您的超链接时,请使用 encodeURIComponent ex。

"<a href=\"#\" onclick=\"passSearchTerm('" + encodeURIComponent(aa) + "')\">View</a>"

and while retriving use decodeURIComponent

并在检索时使用 decodeURIComponent

function passSearchTerm(aa) { alert(decodeURIComponent(aa)); }

回答by Mesh

I think you've just overused your escapes.

我认为你只是过度使用了你的逃避。

This works for me.

这对我有用。

  var aa = 'TAGS("a b")'; 
  // var aa =  'TAGS(\"a b\")'; 

  var e = document.createElement("A");
  e.href = "#";
  e.setAttribute( "onClick", "passSearchTerm('" + aa + "');" );
  e.innerText = "View";

  document.body.appendChild(e);

  function passSearchTerm(p){
    alert(p);
  }

</script>

回答by pktangyue

var aa = 'TAGS(\"a&nbsp;b\")';

This code does work. It is because in html space should written as &nbsp;

这段代码确实有效。这是因为在 html 空间中应该写为&nbsp;

[update]

[更新]

Here is the full example. http://jsfiddle.net/YAJNL/

这是完整的示例。http://jsfiddle.net/YAJNL/