【问题标题】:Single quote inside string is incorrectly represented [duplicate]字符串内的单引号表示不正确[重复]
【发布时间】:2017-01-15 09:11:37
【问题描述】:

我有一个 HTML 按钮,在 onclick 事件中我得到的参数很少。我的论点是这样的:

javascript:Email('Andy.n@gmail.com' ,'19','1','2017','106 O'Horg St, Del-5th floor boardroom')

现在问题出在这个值'106 O'Horg St, Del-5th floor boardroom',

因为我的值中有O',所以我的完整字符串已损坏,我无法使用它。谁能帮我解决这个问题? 这是我获取数据和评估的示例代码。

onclick="javascript:Email(\''+facilityOwnerEmail+'\' ,\''+i+'\',\''+monthNumber+'\',\''+yearnum+'\',\''+locArray[j][0]+'\')"

我不能用任何其他字符替换 ',因为它会与后端的数据不匹配。

【问题讨论】:

  • 您必须提供更多信息(代码),说明如何获取此字符串,因为您使用的符号本身已经是语法错误。
  • @user12345,你能发布你的代码吗?
  • @trincot 我在需要 O' 的地方获取此电子邮件数据。我想在这种情况下如何处理,因为如果 value 中没有单引号,那么事情就会完美地工作。
  • 你试过用斜线转义它吗'106 O\'Horg St, Del-5th floor boardroom'
  • @user12345,您应该提供有关如何从电子邮件中获取数据的代码到您所说的这个参数中。发生这种情况的方式有数百种,除非您提供代码,否则我们无法知道哪种方式。

标签: javascript html


【解决方案1】:

几个选项:

改用双引号:

"106 O'Horg  St, Del-5th floor boardroom"

改用反引号(ES6+):

`106 O'Horg  St, Del-5th floor boardroom`

使用\ 转义有问题的单引号:

'106 O\'Horg  St, Del-5th floor boardroom'

【讨论】:

    【解决方案2】:

    您需要转义该字符串中的引号,这会变得相当复杂并导致代码难以阅读。我建议不要这样做,而是使用完全不同的模式来创建这些可点击元素:

    • 不用生成 HTML,而是使用 DOM API 创建元素;
    • 不使用onclick 属性,而是通过代码添加点击监听器(使用.addEventListener()

    如果您这样做,您将不必担心转义引号,因为使用这种工作方法不会评估任何字符串。

    这是一个小例子,其中一个这样的元素被添加到文档中:

    // Dummy Email implementation: you would use your own of course:
    function Email(a, b, c, d, e) {
        console.log('calling Email with following arguments:');
        console.log([a, b, c, d, e].join(','));
    }
    
    // Sample data:
    var facilityOwnerEmail = 'Andy.n@gmail.com',
        i = 19,
        monthNumber = 1,
        yearnum = 2017,
        j = 0,
        locArray = [["106 O'Horg St, Del-5th floor boardroom"]];
    
    // 1. generate clickable element via the DOM API, without the onclick attribute:
    var div = document.createElement('div');
    div.textContent = 'click here';
    // 2. Provide the click handler dynamically, binding the arguments to a copy of the Email function
    //   -- now there is no problem with quotes anymore:
    div.addEventListener('click', Email.bind(null, facilityOwnerEmail,i,monthNumber,yearnum,locArray[j][0]));
    // 3. add that element to your document, at the desired place (I chose body as example):
    document.body.appendChild(div);
    // For any other such elements to generate, repeat the above three steps
    // ...

    【讨论】:

      猜你喜欢
      • 2012-01-11
      • 2014-09-26
      • 2012-11-24
      • 2020-11-06
      • 1970-01-01
      • 1970-01-01
      • 2013-02-09
      • 2015-11-03
      • 2014-05-02
      相关资源
      最近更新 更多