In my javascript code, I have a variable which have a string. String contains ' or quote in it. Example

在我的javascript代码中,我有一个变量,它有一个字符串。字符串包含“或引用它”。例子

var name= "hi's";

I am creating a link dynamically in a code. where it is written as a string i.e a variable content will be used dynamically to create a link on html page.

我在代码中动态创建一个链接。它被写成字符串i。一个变量的内容将被动态地使用,以在html页面上创建一个链接。

content= '<a onclick="javascript:fun(\'' + name + '\');">'

Here it is giving problem that quote in variable name completes the string in content. and hence rest portion of content is not recognised..

这里给出的问题是,变量名中的引用完成了内容中的字符串。因此,其余部分的内容不被认可。

similar problem arises if var name = 'hi"s'; i.e. if double quote is present in it.

如果var name = 'hi ',则出现类似的问题;也就是说,如果有双引号。

plz help

请帮助

1 个解决方案

#1


3

This is how you would create an anchor properly and completely avoid the need to escape anything.

这就是你如何正确地创建一个锚,并且完全避免了逃避任何事情的需要。

var name = "Hi's",
anchor = document.createElement('a');

// should have an href
// links will be displayed differently by some browsers without it
anchor.href = '#';
// using onclick for pragmatic reasons
anchor.onclick = function() {
    fun(name);
    return false;
}
anchor.innerHTML = 'hello world';

// later
mydiv.appendChild(anchor);

Btw, the onclick attribute shouldn't start with "javascript:" at all; that's already implied.

顺便说一下,onclick属性不应该以“javascript:”开头;这是已经暗示。

Update

更新

If you're still interested in the inline version, variables need two steps of encoding:

如果您仍然对内联版本感兴趣,变量需要两步编码:

  1. The first is to serialize the variable properly; I would use JSON.stringify() for that

    第一个是正确地序列化变量;我会用JSON.stringify()来表示。

  2. The second is HTML escaping; the simplest form is simply to replace double quotes with their proper encoded values.

    第二个是HTML转义;最简单的形式就是用正确的编码值替换双引号。

For example:

例如:

var content = '<a href="#" onclick="fun(' + 
    JSON.serialize(name).replace(/"/g, '&quot;') + ');">hello</a>';

更多相关文章

  1. 如何截取html的子字符串作为内容摘要
  2. 如果字符串包含html代码,如何用python检测?
  3. jquery将html转换为字符串和html
  4. 如何将标记中的值传递给PHP变量?
  5. js去除字符串中所有html标签及 符号
  6. 用JAVA从HTML标记中撕下子字符串
  7. js去掉html标签和去掉字符串文本的所有的空格
  8. knitr html输出中的字符串太长
  9. 从数组中构建越来越长的字符串

随机推荐

  1. android socket通信
  2. Android应用程序消息处理机制(Looper、Han
  3. Android基本操作1(意图使用、界面转换、按
  4. 第十七章 Android 常见的Service
  5. 全家桶!阿里P8大佬熬夜15天,把所有Android
  6. Tensorflow在手机端的部署——官网Androi
  7. android SQLite存储简单范例+详细注释(增
  8. Android ImageView 图片等比缩放问题
  9. Google Docs 更新,提供 Honeycomb 平板更
  10. 《疯狂Android讲义》